package com.nhc.activity_fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.astrob.NavFrameSDK;
import com.astrob.activitys.AppContext;
import com.astrob.activitys.GPSProvider;
import com.astrob.activitys.PositionProvider;
import com.astrob.model.HistoryData;
import com.astrob.model.HistoryData2;
import com.astrob.model.HistoryFileHandle;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.Car;
import com.astrob.view.MapViewS;
import com.astrob.view.NaviInfoView;
import com.astrob.view.TipInfoView;
import com.astrob.view.TrackShow;
import com.astrob.view.ZoomView;
import com.iflytek.tts.TtsService.TtsSpeaker;
import com.nhc.database.dbmodel.Measure;
import com.nhc.database.dbmodel.MeasurePoint;
import com.nhc.database.dbmodel.QiyaInfo;
import com.nhc.database.dbmodel.Route;
import com.nhc.database.dbmodel.SystemAllInfo;
import com.nhc.database.dbmodel.TrackPoint;
import com.nhc.database.dbmodel.WayPoint;
import com.nhc.database.dbmodel.WayTrail;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.database.manager.MeasureCenter;
import com.nhc.database.manager.QiyaCenter;
import com.nhc.database.manager.SystemCenter;
import com.nhc.model.MapSetInfo;
import com.nhc.model.NaviTrackSetInfo;
import com.nhc.model.PaomaoInfo;
import com.nhc.model.PoiCollectInfo;
import com.nhc.model.TransParaSeven;
import com.nhc.model.TripDataFileHandle;
import com.nhc.model.TripDatainfo;
import com.nhc.view.CompassView;
import com.nhc.view.MultiMapView;
import com.nostra13.universalimageloader.utils.L;

import org.mapsforge.core.graphics.Style;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.util.MercatorProjection;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.layer.Layer;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.Polyline;
import org.osmdroid.views.overlay.simplefastpoint.LabelledGeoPoint;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import zuo.biao.library.base.BaseFragment;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.StringUtil;

import static android.content.Context.SENSOR_SERVICE;

public class MainMapFragment extends BaseFragment implements PositionProvider.PosCallBack, View.OnClickListener, SensorEventListener,
        zuo.biao.library.ui.AlertDialog.OnDialogButtonClickListener {
    private final String TAG = "MainMapFragment";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static MainMapFragment createInstance() {
        return new MainMapFragment();
    }

    Handler mFHandler = null;// for 双击全屏显示

    public void setFatherHandler(Handler fHandler) {
        mFHandler = fHandler;
    }

    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.mainmap_fragment);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        return view;//返回值必须为view
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    MultiMapView mMultiMapView;
    ZoomView mZoom;
    NaviInfoView mNaviInfoView;

    TextView mLocal;
    TextView mScale;
    ImageView iv_center;
    TextView ibt_addmark;
    TextView tv_navitrackreturnback;
    TextView ibt_rec_begin;
    TextView ibt_rec_pause;
    TextView ibt_rec_stop;
    TextView tv_center_lonlat;
    TextView tv_centertolocal_distance;
    TextView tv_topinfo_dir;
    TextView tv_measure_info;
    TipInfoView mTipInfo;
    private TextView tv_tile;

    CompassView mCompass;


    Button bt_menuitem_5;//显示关闭数据区
    TextView btn_realtimearea_pause;
    TextView tv_navilineclose;
    TextView tv_navitrackclose;
    private TextView overNavibtn;

    boolean _showtopinfo = true;

    @Override
    public void initView() {//必须在onCreateView方法内调用
        mMultiMapView = (MultiMapView) findViewById(R.id.id_multimap);

        mNaviInfoView = (NaviInfoView) findViewById(R.id.id_naviinfo);
        mTipInfo = (TipInfoView) findViewById(R.id.id_tipinfoview);
        overNavibtn = (TextView) findViewById(R.id.btnnaviover);
        overNavibtn.setTypeface(AppContext.getInstances().getIconfont());

        mMultiMapView.mMapViewS.setNeedPopTipInfo(false);//单击无需弹出tip

        tv_tile = (TextView) findViewById(R.id.tv_tile);
        tv_tile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onChangeTile();
            }
        });

        mZoom = (ZoomView) findViewById(R.id.id_zoomview);
        mScale = (TextView) findViewById(R.id.id_map_scalebar);
        mLocal = (TextView) findViewById(R.id.btnlocal);
        iv_center = (ImageView) findViewById(R.id.iv_center);
        ibt_addmark = (TextView) findViewById(R.id.ibt_addmark);
        tv_navitrackreturnback = (TextView) findViewById(R.id.tv_navitrackreturnback);
        ibt_rec_begin = (TextView) findViewById(R.id.ibt_rec_begin);
        ibt_rec_pause = (TextView) findViewById(R.id.ibt_rec_pause);
        ibt_rec_stop = (TextView) findViewById(R.id.ibt_rec_stop);
        tv_center_lonlat = (TextView) findViewById(R.id.tv_center_lonlat);
        tv_centertolocal_distance = (TextView) findViewById(R.id.tv_centertolocal_distance);
        tv_topinfo_dir = (TextView) findViewById(R.id.tv_topinfo_dir);
        tv_measure_info = (TextView) findViewById(R.id.tv_measure_info);
        bt_menuitem_5 = (Button) findViewById(R.id.bt_menuitem_5);

        btn_realtimearea_pause = (TextView) findViewById(R.id.btn_realtimearea_pause);


        mCompass = (CompassView) findViewById(R.id.compass_pointer);

        tv_navilineclose = (TextView) findViewById(R.id.tv_navilineclose);
        tv_navilineclose.setTypeface(AppContext.getInstances().getIconfont());
        tv_navilineclose.setText(R.string.fonticon_more_naviline);

        tv_navitrackclose = (TextView) findViewById(R.id.tv_navitrackclose);
        tv_navitrackclose.setTypeface(AppContext.getInstances().getIconfont());
        tv_navitrackclose.setText(R.string.fonticon_more_navitrack);

        initMapEngin();
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initData() {//必须在onCreateView方法内调用

    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用

        LonLat centerLL = SysUtils.getInstance().getLL();
        mCar.navpos_.pos.lon = centerLL.GetLon();
        mCar.navpos_.pos.lat = centerLL.GetLat();
        mMultiMapView.setMapCenter(centerLL);
        try {
            Start.getInstance().MapKit().setScale(100000);
        } catch (Exception e) {
            System.exit(0);
            return;
        }
        mCar.setCQY(0.5f);

        mZoom.setOnClickListener(this);
        mLocal.setOnClickListener(this);
        overNavibtn.setOnClickListener(this);
        ibt_addmark.setOnClickListener(this);
        tv_navitrackreturnback.setOnClickListener(this);
        ibt_rec_begin.setOnClickListener(this);
        ibt_rec_pause.setOnClickListener(this);
        ibt_rec_stop.setOnClickListener(this);
        mNaviInfoView.setOnClickListener(this);
        btn_realtimearea_pause.setOnClickListener(this);
        tv_navilineclose.setOnClickListener(this);
        tv_navitrackclose.setOnClickListener(this);
        mTipInfo.setOnClickListener(this);

        findViewById(R.id.bt_topinfo_menu).setOnClickListener(this);
        findViewById(R.id.bt_menuitem_0).setOnClickListener(this);
        findViewById(R.id.bt_menuitem_1).setOnClickListener(this);
        findViewById(R.id.bt_menuitem_2).setOnClickListener(this);
        findViewById(R.id.bt_menuitem_3).setOnClickListener(this);
        findViewById(R.id.bt_menuitem_4).setOnClickListener(this);
        findViewById(R.id.bt_menuitem_5).setOnClickListener(this);
        findViewById(R.id.bt_menuitem_6).setOnClickListener(this);
        findViewById(R.id.bt_menuitem_7).setOnClickListener(this);
        findViewById(R.id.ll_mainmap_popmenu).setOnClickListener(this);

        findViewById(R.id.btn_measure_close).setOnClickListener(this);
        findViewById(R.id.btn_measure_addone).setOnClickListener(this);
        findViewById(R.id.btn_measure_closeone).setOnClickListener(this);
        findViewById(R.id.btn_measure_save).setOnClickListener(this);
        findViewById(R.id.btn_realtimearea_close).setOnClickListener(this);


        // 取得SensorManager实例
        mRegisteredSensor = false;
        mSensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE);

        _showtopinfo = SysUtils.getInstance().getIsShowtopinfo();
        showTopCtrl();
        initWnd(MOVING_MODE);

        //是否继续前次导航
        SystemAllInfo sInfo = SystemCenter.getInstance().getSysInfo("HistoryData2");
        if (sInfo != null) {
            String strHistoryData = sInfo.getContent();
            HistoryData2 historyData = JSON.parseObject(strHistoryData, HistoryData2.class);
            if (historyData != null && historyData.getLl().IsValid()) {
                WayPoint makerNavi = new WayPoint();
                DBDataCenter.getInstance().makerNavi = makerNavi;
                LonLat destLLgcj02 = historyData.getLl();
                LonLat destLL = Utils.gcj02towgs84(destLLgcj02.GetLon(), destLLgcj02.GetLat());
                makerNavi.setLL(destLL.GetLon(), destLL.GetLat());
                makerNavi.setName(historyData.getName());
                Start.getInstance().MapKit().mNavDest = new NavFrameSDK.NavDest[1];
                Start.getInstance().MapKit().mNavDest[0] = NavFrameSDK.getInstance().new NavDest();
                Start.getInstance().MapKit().mNavDest[0].pos.lon = destLLgcj02.GetLon();
                Start.getInstance().MapKit().mNavDest[0].pos.lat = destLLgcj02.GetLat();
                Start.getInstance().MapKit().mNavDest[0].name = historyData.getName();
                Start.getInstance().MapKit().mNavDest[0].eid = 0;
                Start.getInstance().MapKit().clearNavStart();
                mHandler.sendEmptyMessage(Msg.BEGINROUTE);
            }
        }
    }

    // MapMode -- 移图模式/导航模式
    public final int MOVING_MODE = 0;
    public final int NAVI_MODE = 1;
    public int mMapMode = -1;

    private void initWnd(int mapMode) {
        mMapMode = mapMode;

        removeTip();

        if (MOVING_MODE == mapMode) {
            mNaviInfoView.setVisibility(View.GONE);
            mTipInfo.setVisibility(View.GONE);
            mTipInfo.setData(null);

            if (SysUtils.getInstance().mapsource == 1000) {
                Start.getInstance().MapKit().setRotation(0);
                // 回2D模式
                Start.getInstance().MapKit().setMapViewMode(0);
            } else {
                mMultiMapView.setMapOrientation(0);
            }

            mCar.setFreeMoving(true);
//            iv_center.setVisibility(View.VISIBLE);
            mLocal.setSelected(false);
        } else if (NAVI_MODE == mapMode) {
            iv_center.setVisibility(View.GONE);
            mLocal.setSelected(true);
            mCar.setFreeMoving(false);
            if (Start.getInstance().isHavePath()) {
                mNaviInfoView.setVisibility(View.VISIBLE);
            }
            mTipInfo.setVisibility(View.GONE);
            mTipInfo.setData(null);
//            Start.getInstance().MapKit().setScale(100000);
//            mZoom.updateState(0);

            mMultiMapView.setMapCenter(mCar.getCarLL());
            if (mCar.getCarposMode() == Car.BOTTOMCENTER) {
                mMultiMapView.setMapOrientation((float)mCar.navpos_.dir);
            }
        }
        updateMapView();
    }

    private void showRecCtrl() {
        //是否需要显示航迹控件
        findViewById(R.id.ll_rec).setVisibility(View.VISIBLE);
    }

    private void showTopCtrl() {
        //是否需要显示数据区
        if (_showtopinfo) {
            findViewById(R.id.ll_mainmap_topinfo).setVisibility(View.VISIBLE);
            bt_menuitem_5.setText(R.string.gbsjq);
        } else {
            findViewById(R.id.ll_mainmap_topinfo).setVisibility(View.GONE);
            bt_menuitem_5.setText(R.string.xssjq);
        }

    }

    private void setMeasureMode(int measureMode) {
        initWnd(MOVING_MODE);
        mMeasureMode = measureMode;
        //正常移图模式
        findViewById(R.id.ll_measure).setVisibility(View.GONE);
        findViewById(R.id.ll_measure_bottom).setVisibility(View.GONE);
        showTopCtrl();
        showRecCtrl();
        removeTip();
        mTipInfo.setVisibility(View.GONE);
        mTipInfo.setData(null);
        ibt_addmark.setVisibility(View.VISIBLE);
        Start.getInstance().mMeasurelist.clear();
        iv_center.setVisibility(View.GONE);

        switch (mMeasureMode) {
            default:
            case 0:
                if (mFHandler != null) {
                    mFHandler.sendEmptyMessage(Msg.DOSHOWTAB);
                }
                break;
            case 1:
                findViewById(R.id.ll_measure).setVisibility(View.VISIBLE);
                findViewById(R.id.ll_measure_bottom).setVisibility(View.VISIBLE);
                findViewById(R.id.ll_rec).setVisibility(View.GONE);
                findViewById(R.id.ll_mainmap_topinfo).setVisibility(View.GONE);
                ibt_addmark.setVisibility(View.GONE);
                tv_measure_info.setText(R.string.juli_t);
                findViewById(R.id.btn_measure_save).setVisibility(View.VISIBLE);
                iv_center.setVisibility(View.VISIBLE);
                if (mFHandler != null) {
                    mFHandler.sendEmptyMessage(Msg.DOHIDETAB);
                }
                break;
            case 2:
                findViewById(R.id.ll_measure).setVisibility(View.VISIBLE);
                findViewById(R.id.ll_measure_bottom).setVisibility(View.VISIBLE);
                findViewById(R.id.ll_rec).setVisibility(View.GONE);
                findViewById(R.id.ll_mainmap_topinfo).setVisibility(View.GONE);
                ibt_addmark.setVisibility(View.GONE);
                findViewById(R.id.btn_measure_save).setVisibility(View.VISIBLE);
                tv_measure_info.setText(R.string.mianji_t);
                if (mFHandler != null) {
                    mFHandler.sendEmptyMessage(Msg.DOHIDETAB);
                }
                iv_center.setVisibility(View.VISIBLE);
                break;
            case 3:
                findViewById(R.id.ll_measure).setVisibility(View.VISIBLE);
                findViewById(R.id.ll_measure_bottom).setVisibility(View.VISIBLE);
                findViewById(R.id.ll_rec).setVisibility(View.GONE);
                findViewById(R.id.ll_mainmap_topinfo).setVisibility(View.GONE);
                ibt_addmark.setVisibility(View.GONE);
                findViewById(R.id.btn_measure_save).setVisibility(View.VISIBLE);
                tv_measure_info.setText(R.string.hxjl_t);
                if (mFHandler != null) {
                    mFHandler.sendEmptyMessage(Msg.DOHIDETAB);
                }
                iv_center.setVisibility(View.VISIBLE);
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Msg.UPDATEPOS:
                    matchPos();
                    break;
                case Msg.SHOWTIP:
                    break;
                case Msg.ONLOCAL:
                    onLocal();
                    break;
                case Msg.UPDATEMAP:
                    updateMapView();
                    break;
                case Msg.FINISHUPDATEMAP:
                    finishUpdatedMapView();
                    break;
                case Msg.BEGINROUTE:
                    onRoute();
                    break;
                case Msg.FINISHROUTE:
                    onFinishRoute();
                    break;
                case Msg.NAVILINENEXT:
                    onNextNaviLine();
                    break;
                case Msg.NAVI2TIP:
                    onNaviW();
                    break;
                case Msg.ADDMARKERW:
                    onADDMARKERW();
                    break;
                case Msg.ADDMARKER:
                    toActivity(MarkerPointActivity.createIntent(getContext()), REQUEST_TO_MARKER);
                    break;
                case Msg.CHANGEMAPINFO: {
                    if (_tipPoint == null) {
                        //没有大头针，显示当前位置的经纬度和高度
                        tv_center_lonlat.setText(SysUtils.getInstance().getLLStr(mCar.getCarLL()));
                        int altitude = (int) GPSProvider.getInstance().getAltitude();

                        String ALT[] = SysUtils.getInstance().getAltitudeStr(altitude);
                        tv_centertolocal_distance.setText(ALT[0] + ALT[1]);
                        tv_topinfo_dir.setText("");
                    } else {
                        LonLat tipLL = mTipInfo.getLL();
                        if (tipLL != null) {
                            LonLat carLL = mCar.getCarLL();
                            tv_center_lonlat.setText(SysUtils.getInstance().getLLStr(tipLL));
                            int distance = (int) Start.getInstance().MapKit().getDistance(tipLL, carLL);
                            String DIS[] = SysUtils.getInstance().getDistanceStr(distance);
                            tv_centertolocal_distance.setText(DIS[0] + DIS[1]);
                            tv_topinfo_dir.setText(Start.getInstance().MapKit().getDirection(carLL, tipLL));
                        }
                    }
                }
                break;
                case Msg.TOMOVINGMODE:
                    initWnd(MOVING_MODE);
                    break;
                case Msg.MAPLEFT:
                    moveMap(-5, 0);
                    break;
                case Msg.MAPRIGHT:
                    moveMap(5, 0);
                    break;
                case Msg.MAPUP:
                    moveMap(0, -5);
                    break;
                case Msg.MAPDOWN:
                    moveMap(0, 5);
                    break;
                case Msg.MAPZOOMIN:
                    onZoomIn();
                    break;
                case Msg.MAPZOOMOUT:
                    onZoomOut();
                    break;

            }
        }
    };

    //有大头针时，点击添加航点按键
    private void onADDMARKERW() {
        if (_tipPoint == null) {
            addMarkerByLocaton();
        } else {
            new AlertDialog(context, "创建航点", "使用当前位置／选中位置。", "选中位置", "当前位置", 1111, this).show();
        }
    }

    private void onNaviW() {
        if (mMeasureMode != 0) {
            measureAddone();
            return;
        }
        tv_center_lonlat.setFocusable(true);
        if (_tipPoint == null) {
            return;
        }
        new AlertDialog(context, "导航提示", "将选中的位置设为目的地。", "是", "否", 2222, this).show();
    }

    private void addMarkerByLocaton() {
        LonLat ll = SysUtils.getInstance().getLL();
        WayPoint wp = DBDataCenter.getInstance().createNewWayPoint(ll);
        wp.setAltitude(GPSProvider.getInstance().getAltitude());
        if (NaviTrackSetInfo.getInstance().isUseqiyagd() && QiyaCenter.getInstance()._thisQiyaInfo != null) {
            double qiyaH = QiyaCenter.getInstance()._thisQiyaInfo.getAltitude();
            double H = wp.getAltitude();
            if (Math.abs((int) (qiyaH - H)) < 100 || H == 0) {
                //气压高度误差太大；可能气压高度是不准确的则不用
                wp.setAltitude(qiyaH);
            }
        }

        if (PoiCollectInfo.getInstance().getSavemode() == 0) {
            DBDataCenter.getInstance().saveWayPoint(wp);
            showShortToast(getString(R.string.tsavenpt));
        } else {
            DBDataCenter.getInstance().makerEdit = wp;
            toActivity(MarkerPointActivity.createIntent(context), 2221);
        }

        if (mHandler != null) {
            mHandler.sendEmptyMessage(Msg.UPDATEMAP);
        }
    }

    private void doAddMarker(boolean isPositive) {
        if (isPositive) {
            //是
            LonLat ll = SysUtils.getInstance().getLL();
            String name = "";
            NavFrameSDK.POIDescription data = mTipInfo.getData();
            if (data != null) {
                ll = mTipInfo.getLL();
                name = data.name;
            }
            addMarkByLL(ll, name);
        } else {
            addMarkerByLocaton();
        }
    }

    private void moveMap(int x, int y) {

        if (!SysUtils.getInstance().is240x320) {
            return;
        }

        if (mMeasureMode != 0) {
            mMultiMapView.moveMap(x, y);
            return;
        }

        if (mMapMode == NAVI_MODE) {
            initWnd(MOVING_MODE);
            return;
        }

        if (_tipPoint == null) {
            _tipPoint = new Point();
            LonLat ll = mMultiMapView.getMapCenter();
            _tipPoint = mMultiMapView.LL2XY(ll);
        }

        int top = 30;
        int bottom = 250;
        int left = 10;
        int right = 220;

        if (mMultiMapView.getMapsource() == 1001) {
            top = 90;
            bottom = 280;
            left = 90;
            right = 270;
        }

        _tipPoint.x += x;
        _tipPoint.y += y;
        if (_tipPoint.x < left) {
            _tipPoint.x = left;
            mMultiMapView.moveMap(x, y);
        }

        if (_tipPoint.x > right) {
            _tipPoint.x = right;
            mMultiMapView.moveMap(x, y);
        }

        if (_tipPoint.y < top) {
            _tipPoint.y = top;
            mMultiMapView.moveMap(x, y);
        }

        if (_tipPoint.y > bottom) {
            _tipPoint.y = bottom;
            mMultiMapView.moveMap(x, y);
        }

        if (mMultiMapView.getMapsource() == 1000) {
            resetTipInfo();
        } else {
            resetTipInfo2(true);
        }

    }

    public Handler getHandler() {
        return mHandler;
    }

    private void updateMapView() {
        if (SysUtils.getInstance().mapsource == 1000 || SysUtils.getInstance().mapsource == 1001) {
            mScale.setVisibility(View.VISIBLE);
        } else {
            mScale.setVisibility(View.GONE);
        }
        mMultiMapView.updateMap();
    }

    private void finishUpdatedMapView() {
        if (mMultiMapView.getMapsource() != 1000) {
            mZoom.updateState(0);
        } else {
            mZoom.updateState();
        }

        mScale.setText(mMultiMapView.getScaleString());

        if (NAVI_MODE == mMapMode) {
            tv_center_lonlat.setText(SysUtils.getInstance().getLLStr(mCar.getCarLL()));
            int altitude = (int) GPSProvider.getInstance().getAltitude();
            String ALT[] = SysUtils.getInstance().getAltitudeStr(altitude);
            tv_centertolocal_distance.setText(ALT[0] + ALT[1]);
            tv_topinfo_dir.setText("");

            if (mCar.getCarposMode() == Car.BOTTOMCENTER) {
                float degree = (float) mCar.navpos_.dir * -1.0f;
                degree = (degree + 720) % 360;
                mCompass.updateDirection((int) degree);
            }
        } else {
            mCompass.updateDirection(0);
        }

    }

    int _auto2navimodeTime = 0;// 有GPS情况下15s无操作，回现在地

    int _lastGpsstate = -1;//0-未定位 1-已经定位

    @Override
    public void updatePos(NavFrameSDK.NavPosition navpos, boolean isNetPos) {

        _havepos = false;
        if (navpos != null) {
            mCar.navpos_ = navpos;
            _havepos = true;

            if (_lastGpsstate == 0 && !isNetPos) {
                TtsSpeaker.getInstance().talk(getString(R.string.wxjszc));
            }
            _lastGpsstate = 1;
        } else {
            mCar.navpos_.signal = 100;

            if (_lastGpsstate == 1) {
                TtsSpeaker.getInstance().talk(getString(R.string.sqwxxh));
            }
            _lastGpsstate = 0;
        }
        mHandler.sendEmptyMessage(Msg.UPDATEPOS);
    }

    int mRecNum = 0;//轨迹记录闪烁计数

    void animRec() {
        mRecNum++;
        if (mRecState == 1) {
            if (mRecNum > 1) {
                mRecNum = 0;
                ibt_rec_begin.setVisibility(View.VISIBLE);
            } else {
                ibt_rec_begin.setVisibility(View.GONE);
            }
        } else {
            ibt_rec_begin.setVisibility(View.VISIBLE);
        }
    }

    int alarmWayTrail = -1;
    int matchWayTrailIndex = -1;

    void matchvoidWayTrail() {

        if (MOVING_MODE == mMapMode) {
            return;
        }

        if (DBDataCenter.getInstance().wayTrailNavi == null
                || DBDataCenter.getInstance().wayTrailNavi.trackPointList == null) {
            return;
        }

        LonLat ll = mCar.getCarLL();
        if (ll.IsInvalid()) {
            return;
        }
        matchWayTrailIndex = -1;
        int phfz = (int)NaviTrackSetInfo.getInstance().getPhfz();//米
        ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().wayTrailNavi.trackPointList;
        double minD = 9999999;//30米范围
        TrackPoint lasttp = null;
        for (int i = 0; i < trackPointList.size(); i++) {
            TrackPoint tp = trackPointList.get(i);
            double xlon = Math.abs(tp.getLongitude() - ll.GetLon());
            double xlat = Math.abs(tp.getLatitude() - ll.GetLat());
            double minX = Math.min(xlon, xlat);
            if (minX > 0.01) {
                int stepX = (int) (minX / 0.01);
                int step = 30 * stepX;//1公里外的点，30秒
                if (lasttp != null) {
                    step = (int) (lasttp.getDatetime() - tp.getDatetime()) / 1000;
                    if (step == 0) {
                        step = 1;
                    }
                    step = 30 * stepX / Math.abs(step);
                }
                i += step;
                lasttp = tp;
                continue;
            }

            double distance = Start.getInstance().MapKit().getDistance(tp.getLL(), ll);
            if (minD < distance) {
                minD = distance;
                matchWayTrailIndex = i;
            }
            lasttp = tp;
        }

        if (minD > phfz) {
            alarmWayTrail++;
            if (alarmWayTrail == 0) {
                TtsSpeaker.getInstance().talk(getString(R.string.nyplhjlx));
            } else if (alarmWayTrail % 6 == 0) {
                if (context != null) {
                    MediaPlayer mediaPlayer01;
                    mediaPlayer01 = MediaPlayer.create(context, R.raw.notify);
                    mediaPlayer01.start();
                }
            }
        } else {
            alarmWayTrail = -1;
        }
    }

    void matchPos() {
        if (mMeasureMode > 0) {
            _auto2navimodeTime = 0;
        }

        if (Start.getInstance().isHavePath()) {
            overNavibtn.setVisibility(View.VISIBLE);
        } else {
            overNavibtn.setVisibility(View.GONE);
        }

        PaomaoInfo.getInstance().alarm(context);
        DBDataCenter.getInstance().alarmWarning(context);

//        animRec();
        if (!_havepos) {
            updateMapView();
            return;
        }

//        _auto2navimodeTime++;
//        if (MOVING_MODE == mMapMode) {
//            if (_auto2navimodeTime > 15) {
//                initWnd(NAVI_MODE);
//            }
//            mMultiMapView.updateMap();
//            return;
//        }

        matchvoidWayTrail();

        //为了记录航迹时，车标在航迹线上，车标不匹配道路
        NavFrameSDK.NavPosition matchedPosCar = NavFrameSDK.getInstance().new NavPosition();//车标的火星位置
        LonLat LL = new LonLat(mCar.navpos_.pos.lon, mCar.navpos_.pos.lat);
        matchedPosCar.vel = mCar.navpos_.vel;
        matchedPosCar.signal = mCar.navpos_.signal;
        matchedPosCar.dir = mCar.navpos_.dir;
        LL = Utils.wgs84togcj02(LL.GetLon(), LL.GetLat());//Utils GPS to 火星坐标
        matchedPosCar.pos.lon = LL.GetLon();
        matchedPosCar.pos.lat = LL.GetLat();

        NavFrameSDK.NavPosition matchedPos = NavFrameSDK.getInstance().new NavPosition();
        NavFrameSDK.NavInfo navInfo = NavFrameSDK.getInstance().new NavInfo();
        NavFrameSDK.SDCurPosStates state = NavFrameSDK.SDCurPosStates.SDCURPOSSTATE_NONE;
        try {
            state = Start.getInstance().MapKit().UpdatePosition(matchedPosCar, matchedPos,
                    navInfo);
        } catch (Exception e) {
            return;
        }

        if (Start.getInstance().isHavePath()) {
            double distanceToDest = 0;
            LonLat LLA = null;//起点 火星坐标
            LonLat LLB = null;//目的地
            LonLat LLC = new LonLat(matchedPosCar.pos.lon, matchedPosCar.pos.lat);//车
            if (Start.getInstance().MapKit().mNavDest != null) {
                //此版本都是单目的地，航线导航也是一个到达后再计算另一个
                LLA = new LonLat(Start.getInstance().MapKit().mNavStart.pos.lon, Start.getInstance().MapKit().mNavStart.pos.lat);
                LLB = new LonLat(Start.getInstance().MapKit().mNavDest[0].pos.lon, Start.getInstance().MapKit().mNavDest[0].pos.lat);
                distanceToDest = Start.getInstance().MapKit().getDistance(LLB, LLC);
            } else {
                //没有目的地
                return;
            }
            if (state == NavFrameSDK.SDCurPosStates.SDCURPOSSTATE_DEVIATE) {
                if (SysUtils.getInstance().navi_mode1 == 1) {
                    Start.getInstance().MapKit().reroute(false);
                }
                return;
            } else if (state == NavFrameSDK.SDCurPosStates.SDCURPOSSTATE_ARRIVED_DEST) {
                Start.getInstance().MapKit().clearRoute();
                Start.getInstance().MapKit().clearNavStart();
            }

            if (SysUtils.getInstance().navi_mode1 == 1) {
                //当前目标
                TripDataFileHandle.getInstance().mTripDatainfo.setDqmb(navInfo.turnInfo.toRoadName);
                //当前距离
                TripDataFileHandle.getInstance().mTripDatainfo.setDqjl(navInfo.guidInfo.distanceToTurn);
            } else {
                TripDataFileHandle.getInstance().mTripDatainfo.setDqjl(distanceToDest);
            }

            //没有路径还继续红线导航
            if (distanceToDest < 20) {
                Start.getInstance().MapKit().mNavDest = null;
                Start.getInstance().setHavePath(false);
                TtsSpeaker.getInstance().talk(getString(R.string.nyddmddfj));
                showShortToast(getString(R.string.nyddmddfj));
                if (_isNaviByRoute) {
                    mHandler.sendEmptyMessage(Msg.NAVILINENEXT);
                } else {
                    closeAllPath();
                }
            }

            String sentence = navInfo.sentence;
            if (Start.getInstance().isHavePath() && sentence.length() > 3) {
                TtsSpeaker.getInstance().talk(sentence);
            }

            //设置偏航距
            double pianhz = Utils.pointToLineLL(LLA, LLB, LLC);
            TripDataFileHandle.getInstance().mTripDatainfo.setPianhz(pianhz);
            if (pianhz > 50) {
                //设置返航角
                double fhhx = Start.getInstance().MapKit().getDirection3(LLC, LLB);
                TripDataFileHandle.getInstance().mTripDatainfo.setFhhx(fhhx);
            } else {
                TripDataFileHandle.getInstance().mTripDatainfo.setFhhx(0);
            }

            if (DBDataCenter.getInstance().wayTrailNavi != null) {
                //航迹导航
                navInfo.guidInfo.remainDistance = distanceToDest;
                TripDataFileHandle.getInstance().mTripDatainfo.setRemainDistance(distanceToDest);
            }

            if (SysUtils.getInstance().navi_mode1 == 1) {
                navInfo.guidInfo.distanceToTurn = distanceToDest;
                navInfo.guidInfo.remainDistance = distanceToDest;
                TripDataFileHandle.getInstance().mTripDatainfo.setRemainDistance(distanceToDest);
                if (Start.getInstance().MapKit().mNavDest != null) {
                    navInfo.turnInfo.toRoadName = Start.getInstance().MapKit().mNavDest[0].name;
                }
                navInfo.turnInfo.dirType = NavFrameSDK.TurnDirection.TURN_END;
            }

        } else if (NAVI_MODE == mMapMode) {
            //导航模式下显示，当前位置的高度
            int altitude = (int) GPSProvider.getInstance().getAltitude();
            String ALT[] = SysUtils.getInstance().getAltitudeStr(altitude);
            tv_centertolocal_distance.setText(ALT[0] + ALT[1]);

            tv_topinfo_dir.setText("");
            TripDataFileHandle.getInstance().mTripDatainfo.setPianhz(0);
            TripDataFileHandle.getInstance().mTripDatainfo.setFhhx(0);
            TripDataFileHandle.getInstance().mTripDatainfo.setRemainDistance(0);

            TripDataFileHandle.getInstance().mTripDatainfo.setDqmb(null);
            TripDataFileHandle.getInstance().mTripDatainfo.setDqjl(-1);
        }

        if (MOVING_MODE == mMapMode) {
            updateMapView();
            return;
        }

        if (SysUtils.getInstance().navi_mode1 == 1) {
            mNaviInfoView.setHavepath(Start.getInstance().isHavePath());
        } else {
            mNaviInfoView.setHavepath(false);
        }

        mNaviInfoView.setNavInfo(navInfo, matchedPosCar);

        if (matchedPosCar.vel < 2 && mSensorDegree > 0) {
            matchedPosCar.dir = mSensorDegree;
        }

//        LL = new LonLat(matchedPosCar.pos.lon, matchedPosCar.pos.lat);
//        LL = Utils.gcj02towgs84(LL.GetLon(), LL.GetLat());//Utils GPS to 火星坐标
//        matchedPos.pos.lon = LL.GetLon();
//        matchedPos.pos.lat = LL.GetLat();
//        mCar.setCarNavPos(matchedPos);

        double heading = 0.0;
        if (mCar.getCarposMode() == Car.BOTTOMCENTER) {
            heading = matchedPosCar.dir;
            mCar.setCarHeading((float)heading);
        }

        mMultiMapView.setMapCenter(mCar.getCarLL());
        mMultiMapView.setMapOrientation((float) heading);

        updateMapView();
    }

    private Sensor mPressure;
    private Sensor mTemperature;
    private double mWendu = 0.0;

    @Override
    public void onResume() {
        super.onResume();

        Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mSensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_GAME);
        mSensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_GAME);

        mPressure = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        if (mPressure != null) {
            mSensorManager.registerListener(this, mPressure,
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
//        SENSOR_DELAY_FASTEST——延时：0ms
//        SENSOR_DELAY_GAME——延时：20ms
//        SENSOR_DELAY_UI——延时：60ms
//        SENSOR_DELAY_NORMAL——延时：200ms
        mTemperature = mSensorManager.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
        if (mTemperature != null) {
            mSensorManager.registerListener(this, mTemperature,
                    SensorManager.SENSOR_DELAY_NORMAL);
        }

        PositionProvider.getInstance().mCallback = this;
        mCar.navpos_.pos.lon = SysUtils.getInstance().getLL().GetLon();
        mCar.navpos_.pos.lat = SysUtils.getInstance().getLL().GetLat();

        if (isAddmark) {
            isAddmark = false;
            return;
        }

        try {
            Start.getInstance().MapKit().setMapCenter(SysUtils.getInstance().getLL());
        } catch (Exception e) {
            System.exit(0);
            return;
        }

        mMultiMapView.setMapsource(SysUtils.getInstance().mapsource);

        naviToNavipt();

        naviByRoute();

        naviByNavitrack();

        onInitRec();

        //地图设置
        if (MapSetInfo.getInstance().getMapdirmode() == 0) {
            mCar.setCarposMode(Car.CENTER);
        } else {
            mCar.setCarposMode(Car.BOTTOMCENTER);
        }

        LonLat ll = mCar.getCarLL();
        if(_tipPoint != null) {
            ll = mTipInfo.getLL();
        }
        onChangeMapsource(ll);

        if (MeasureCenter.getInstance().measureRT != null) {
            findViewById(R.id.ll_realtimearea).setVisibility(View.VISIBLE);
            btn_realtimearea_pause.setText(R.string.pause);
            SysUtils.getInstance()._realtimeArea = 1;
        }

        if (mHandler != null) {
            mHandler.sendEmptyMessage(Msg.CHANGEMAPINFO);
        }
    }

    private void naviByNavitrack() {
        if (DBDataCenter.getInstance().wayTrailNavi == null) {
            tv_navitrackclose.setVisibility(View.GONE);
        } else {
//            tv_navitrackclose.setVisibility(View.VISIBLE);
            if (DBDataCenter.getInstance().wayTrailNavi.trackPointList != null) {
                int size = DBDataCenter.getInstance().wayTrailNavi.trackPointList.size();
                if (size > 1) {
                    LonLat llDest = DBDataCenter.getInstance().wayTrailNavi.trackPointList.get(size - 1).getLL();
                    LonLat llStart = DBDataCenter.getInstance().wayTrailNavi.trackPointList.get(0).getLL();
                    if (DBDataCenter.getInstance().wayTrailNavi.isReverse) {
                        llDest = DBDataCenter.getInstance().wayTrailNavi.trackPointList.get(0).getLL();
                        llStart = DBDataCenter.getInstance().wayTrailNavi.trackPointList.get(size - 1).getLL();
                    }
                    llDest = Utils.wgs84togcj02(llDest.GetLon(), llDest.GetLat());
                    Start.getInstance().MapKit().mNavDest = new NavFrameSDK.NavDest[1];
                    Start.getInstance().MapKit().mNavDest[0] = NavFrameSDK.getInstance().new NavDest();
                    Start.getInstance().MapKit().mNavDest[0].pos.lon = llDest.GetLon();
                    Start.getInstance().MapKit().mNavDest[0].pos.lat = llDest.GetLat();

                    ArrayList<NavFrameSDK.POIDescription> poiList = Start.getInstance().MapKit()
                            .getNearPoi(llDest, false);
                    if (poiList.size() > 0) {
                        NavFrameSDK.POIDescription data = poiList.get(0);
                        Start.getInstance().MapKit().mNavDest[0].name = data.name;
                    }
                    Start.getInstance().MapKit().mNavDest[0].eid = 0;

                    llStart = Utils.wgs84togcj02(llStart.GetLon(), llStart.GetLat());
                    Start.getInstance().MapKit().mNavStart.pos.lon = llStart.GetLon();
                    Start.getInstance().MapKit().mNavStart.pos.lat = llStart.GetLat();
                    Start.getInstance().setHavePath(true);
                }
            }

        }
    }


    @Override
    public void onPause() {
        super.onPause();
        PositionProvider.getInstance().mCallback = null;

        if (mRegisteredSensor) {
            // 如果调用了registerListener
            // 这里我们需要unregisterListener来卸载/取消注册
            mSensorManager.unregisterListener(this);
            mRegisteredSensor = false;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnlocal:
                onLocal();
                break;
            case R.id.btnzoomin:
                onZoomIn();
                break;
            case R.id.btnzoomout:
                onZoomOut();
                break;
            case R.id.btnTipcar:
                onTipcar();
                break;
            case R.id.btnTipname:
                onTipname();
                break;
            case R.id.btnTipman:
                onTipman();
                break;
            case R.id.bt_topinfo_menu:
                onPopMenu();
                break;
            case R.id.bt_menuitem_0:
                doPopMenu(0);
                break;
            case R.id.bt_menuitem_1:
//                doPopMenu(1);//面积测量改为实时面积测量
                if (SysUtils.getInstance()._realtimeArea == -1 || MeasureCenter.getInstance().measureRT == null) {
                    findViewById(R.id.ll_realtimearea).setVisibility(View.VISIBLE);
                    btn_realtimearea_pause.setText(R.string.pause);
                    SysUtils.getInstance()._realtimeArea = 1;
                    MeasureCenter.getInstance().measureRT = new Measure("realtimeArea");
                }
                doPopMenu(-1);
                break;
            case R.id.bt_menuitem_2:
                doPopMenu(2);
                break;
            case R.id.bt_menuitem_3:
                doPopMenu(3);
                break;
            case R.id.bt_menuitem_4:
                doPopMenu(4);
                break;
            case R.id.bt_menuitem_5:
                doPopMenu(5);
                break;
            case R.id.bt_menuitem_6:
                doPopMenu(6);
                break;
            case R.id.bt_menuitem_7:
                doPopMenu(-1);
                break;
            case R.id.ll_mainmap_popmenu:
                doPopMenu(-1);
                break;
            case R.id.ibt_addmark:
                addMark();
                break;
            case R.id.ibt_rec_begin:
                onStartRec();
                break;
            case R.id.ibt_rec_pause:
                onPauseRec();
                break;
            case R.id.tv_navitrackreturnback:
                onThisNavitrackreturnback();
                break;
            case R.id.ibt_rec_stop:
                onCloseRec();
                break;
            case R.id.btnnaviover:
                overNavi();
                break;
            case R.id.btn_measure_close:
                setMeasureMode(0);
                break;
            case R.id.btn_measure_addone:
                measureAddone();
                break;
            case R.id.btn_measure_closeone:
                measureCloseone();
                break;
            case R.id.btn_measure_save:
                saveMeasureMenu();
                break;
            case R.id.btn_realtimearea_pause:
                doRealtimeareaPause();
                break;
            case R.id.btn_realtimearea_close:
                doRealtimeareaSave();
                break;
            case R.id.tv_navilineclose:
                onCloseNaviline();
                break;
            case R.id.tv_navitrackclose:
                onCloseNavitrack();
                break;
            default:
                break;
        }
    }

    private void onCloseNaviline() {
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdgbhxdh), true, 98, this).show();
    }

    private void onCloseNavitrack() {
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qdgbhjdh), true, 99, this).show();
    }

    private void doRealtimeareaPause() {
        if (SysUtils.getInstance()._realtimeArea == 0) {
            SysUtils.getInstance()._realtimeArea = 1;
        } else if (SysUtils.getInstance()._realtimeArea == 1) {
            SysUtils.getInstance()._realtimeArea = 0;
        }

        if (SysUtils.getInstance()._realtimeArea == 0) {
            btn_realtimearea_pause.setText(R.string.jixu);
        } else if (SysUtils.getInstance()._realtimeArea == 1) {
            btn_realtimearea_pause.setText(R.string.pause);
        }
    }

    private void doRealtimeareaSave() {
        findViewById(R.id.ll_realtimearea).setVisibility(View.GONE);
        SysUtils.getInstance()._realtimeArea = -1;

        Measure measureRT = MeasureCenter.getInstance().measureRT;
        if (measureRT == null || measureRT.measurePtList == null
                || measureRT.measurePtList.size() < 2) {
            showShortToast(getString(R.string.celiang_toast_0));
            MeasureCenter.getInstance().measureRT = null;
            return;
        }

        intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                , getString(R.string.sscl_name), SysUtils.getInstance().getTimeStr(System.currentTimeMillis()));
        toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO2, false);

    }

    private void measureSaveRt(String name) {
        findViewById(R.id.ll_realtimearea).setVisibility(View.GONE);
        SysUtils.getInstance()._realtimeArea = -1;

        Measure measureRT = MeasureCenter.getInstance().measureRT;
        if (measureRT == null || measureRT.measurePtList == null
                || measureRT.measurePtList.size() < 2) {
            showShortToast(getString(R.string.celiang_toast_0));
            return;
        }
        if (name != null && name.length() > 1) {
            measureRT.setName(name);
        }
        final Long measureId = MeasureCenter.getInstance().saveMeasure(measureRT);

        showProgressDialog(R.string.saving);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                Measure measure = MeasureCenter.getInstance().getMeasureById(measureId);
                ArrayList<LonLat> measureList = new ArrayList<LonLat>();
                int size = measure.measurePtList.size();
                for (int i = 0; i < size; i++) {
                    MeasurePoint mp = measure.measurePtList.get(i);
                    mp.setMeasure_id(measureId);
                    MeasureCenter.getInstance().saveMeasurePoint(mp);
                    measureList.add(mp.getLL());
                }
                measure.num = size;
                measure.setLength(Utils.calculateLen(measureList));
                if (measure.getType() != 0) {
                    measure.setPerimeter(Utils.calculatePerimeter(measureList));
                    measure.setArea(Utils.calculateArea(measureList));

                    if (measure.getAreatype() == 1) {
                        double area = Utils.calculateAreaByWidth(measureList, measure.getWidth());
//                        double len = Utils.calculateLenAB(measureList);
                        measure.setAreade(area);
//                        measure.setLength(len);//等宽面积，长度
                    } else if (measure.getAreatype() == 2) {

                    }
                }
                MeasureCenter.getInstance().saveMeasure(measure);

                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showShortToast(getString(R.string.ssclsjybc));
                        findViewById(R.id.ll_realtimearea).setVisibility(View.GONE);
                        SysUtils.getInstance()._realtimeArea = -1;
                        toActivity(MeasureInfoActivity.createIntent(context, measureId));
                        MeasureCenter.getInstance().measureRT = null;
                    }
                });
            }
        });

    }

    private void measureSave(String name) {
        int size = Start.getInstance().mMeasurelist.size();
        if (size < 2) {
            showShortToast(getString(R.string.celiang_toast_0));
            return;
        }

        int mode = 0;
        if (mMeasureMode == 2) {
            mode = 1;
        }
        Long measureId = MeasureCenter.getInstance().addNewMeasure();
        Measure measure = MeasureCenter.getInstance().getMeasureById(measureId);
        if (name != null && name.length() > 1) {
            measure.setName(name);
        }

        for (int i = 0; i < size; i++) {
            LonLat ll = Start.getInstance().mMeasurelist.get(i);
            MeasurePoint measurePoint = new MeasurePoint(ll, measureId);
            MeasureCenter.getInstance().saveMeasurePoint(measurePoint);
        }
        measure.num = size;

        measure.setLength(Utils.calculateLen(Start.getInstance().mMeasurelist));
        if (mode == 1) {
            measure.setPerimeter(Utils.calculatePerimeter(Start.getInstance().mMeasurelist));
            measure.setArea(Utils.calculateArea(Start.getInstance().mMeasurelist));
        }
        measure.setType(mode);
        MeasureCenter.getInstance().saveMeasure(measure);

        showShortToast(getString(R.string.ssclsjybc));

        toActivity(MeasureInfoActivity.createIntent(context, measureId), REQUEST_TO_MEASUREINFO);

    }

    private void saveMeasureMenu() {
        if (Start.getInstance().mMeasurelist.size() < 2) {
            setMeasureMode(0);
        } else if (mMeasureMode == 1 || mMeasureMode == 2) {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qsavemesure), true, 60, this).show();
        } else if (mMeasureMode == 3) {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qsaveline), true, 6, this).show();
        }
    }

    //加入的点火星坐标转换后，在最大比例尺会和地图中心图标有偏差
    LonLat _measureLL = null;//测绘加入的最后一个点，移图后，这个置null;
    boolean _measureisgcj02 = false;//测绘加入时，_measureLL的坐标是否为火星坐标

    private void measureAddone() {
        LonLat ll = mMultiMapView.getMapCenter();
        _measureLL = new LonLat(ll.GetLon(), ll.GetLat());
        _measureisgcj02 = mMultiMapView.isgcj02;
        if (mMultiMapView.isgcj02) {
            ll = Utils.gcj02towgs84(ll.GetLon(), ll.GetLat());
        }
        Start.getInstance().mMeasurelist.add(ll);

        refreshMeasureInfo();
        updateMapView();
    }

    private void refreshMeasureInfo() {
        if (mMeasureMode == 1) {
            double len = Utils.calculateLen(Start.getInstance().mMeasurelist);
            String DIS[] = SysUtils.getInstance().getDistanceStr((int) len);
            tv_measure_info.setText(getString(R.string.juli_t) + DIS[0] + DIS[1]);
        } else if (mMeasureMode == 2) {
            double area = Utils.calculateArea(Start.getInstance().mMeasurelist);
            String AREA[] = SysUtils.getInstance().getAreaStr(area);
            tv_measure_info.setText(getString(R.string.mianji_t) + AREA[0] + AREA[1]);
        } else if (mMeasureMode == 3) {
            double len = Utils.calculateLen(Start.getInstance().mMeasurelist);
            String DIS[] = SysUtils.getInstance().getDistanceStr((int) len);
            tv_measure_info.setText(getString(R.string.hxjl_t) + DIS[0] + DIS[1]);
        }
    }

    private void measureCloseone() {
        _measureLL = null;
        int size = Start.getInstance().mMeasurelist.size();
        if (size < 1)
            return;

        Start.getInstance().mMeasurelist.remove(size - 1);
        refreshMeasureInfo();
        updateMapView();
    }

    public void doPopMenu(int pos) {
        switch (pos) {
            default:
                break;
            case 0:
                setMeasureMode(1);
                break;
            case 1:
                setMeasureMode(2);
                break;
            case 2:
                setMeasureMode(3);
                break;
            case 3:
                onMapSetting();
                break;
            case 4:
                clearWayTrail();
                break;
            case 5:
                onTopinfoShow();
                break;
            case 6:
                onDownloadMap();
                break;

        }
        findViewById(R.id.ll_mainmap_popmenu).setVisibility(View.GONE);
    }

    private void onDownloadMap() {
        toActivity(DownloadMapActivity.createIntent(context, 0), 333);
    }

    private void onMapSetting() {
        doPopMenu(-1);
        toActivity(MapSettingActivity.createIntent(context), REQUEST_TO_MAPSET);
    }

    private void clearWayTrail() {
        if (DBDataCenter.getInstance().wayTrailThis != null) {
            DBDataCenter.getInstance().wayTrailThis.reset();
            DBDataCenter.getInstance().doDeleteWayTrailTP(DBDataCenter.getInstance().wayTrailThis.getId());
        }
        showShortToast("当前航迹已清空。");
    }

    public void onPopMenu() {
        findViewById(R.id.ll_mainmap_popmenu).setVisibility(View.VISIBLE);
        findViewById(R.id.bt_menuitem_0).requestFocus();
    }

    public boolean isShownPopMenu() {
        return findViewById(R.id.ll_mainmap_popmenu).isShown();
    }

    private void onTopinfoShow() {
        _showtopinfo = !_showtopinfo;
        SysUtils.getInstance().setIsShowtopinfo(_showtopinfo);
        findViewById(R.id.ll_mainmap_topinfo).setVisibility(View.GONE);
        showTopCtrl();
    }

    void onLocal() {
        if (Utils.isFastDoubleClick())
            return;

        LonLat ll = mCar.getCarLL();

        if (mHandler != null) {
            mHandler.sendEmptyMessage(Msg.CHANGEMAPINFO);
        }

        if (mMeasureMode == 0) {
            initWnd(NAVI_MODE);
            if (Start.getInstance().isHavePath()) {
                mCar.navpos_.pos.lon = ll.GetLon();
                mCar.navpos_.pos.lat = ll.GetLat();
                mCar.navpos_.signal = 6;
                if (GPSProvider.getInstance().isFixed()) {
                    mCar.navpos_.vel = 2;
                } else {
                    mCar.navpos_.vel = 2000;
                }
                _havepos = true;
                mHandler.sendEmptyMessage(Msg.UPDATEPOS);
            }
        } else {
            mMultiMapView.setMapCenter(ll);
            updateMapView();
        }

    }

    //240x320设备的屏幕中心_tipPoint
    //1001-177x177
    //1000,1002-120x131
    void onZoomIn() {
        if (_tipPoint != null) {
            LonLat ll = mTipInfo.getLL();//原始
            mMultiMapView.setMapCenter(ll);
            LonLat llB = mMultiMapView.getMapCenter();
            _tipPoint = mMultiMapView.LL2XY(llB);
        }
        mMultiMapView.zoomIn();
    }

    void onZoomOut() {
        if (_tipPoint != null) {
            LonLat ll = mTipInfo.getLL();
            mMultiMapView.setMapCenter(ll);
            _tipPoint = mMultiMapView.LL2XY(mMultiMapView.getMapCenter());
        }

        mMultiMapView.zoomOut();
    }

    void onTipcar() {
        if (Utils.isFastDoubleClick())
            return;
        NavFrameSDK.POIDescription data = mTipInfo.getData();
        if (data == null) {
            return;
        }
        DBDataCenter.getInstance().makerEdit = DBDataCenter.getInstance().createNewWayPoint(mTipInfo.getLL());

        //周边查询
        toActivity(SearchTypeActivity.createIntent(getContext(), true), REQUEST_TO_SEARCH);
    }

    void onTipname() {
        if (Utils.isFastDoubleClick())
            return;

        if (DBDataCenter.getInstance().makerEdit == null) {
//            NavFrameSDK.POIDescription data = mTipInfo.getData();
//            if (data == null) {
//                return;
//            }
//            DBDataCenter.getInstance().makerEdit = new WayPoint(data);
            onTipman();
        } else {
            toActivity(MarkerPointActivity.createIntent(getContext()), REQUEST_TO_MARKER);
        }

    }

    void onTipman() {
        if (Utils.isFastDoubleClick())
            return;
        NavFrameSDK.POIDescription data = mTipInfo.getData();
        if (data == null) {
            return;
        }

        if (_isNaviByRoute) {
            new AlertDialog(context, "", getString(R.string.qstopdest) + data.name + "]？", true, 11, this).show();
        } else if (DBDataCenter.getInstance().wayTrailNavi != null) {
            new zuo.biao.library.ui.AlertDialog(context, "", getString(R.string.qstopdest) + data.name + "]？", true, 11, this).show();
        } else {
            new AlertDialog(context, getString(R.string.navdest), data.name, true, 11, this).show();
        }

    }

    public void overNavi() {
//        if (_isNaviByRoute) {
//            mHandler.sendEmptyMessage(Msg.NAVILINENEXT);
//        } else {
//            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qovernavi), true, 10, this).show();
//        }

        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qovernavi), true, 10, this).show();
    }

    private void onStartRec() {
        if (mRecState == 1) {
            return;
        }

        if (DBDataCenter.getInstance().wayTrailThis != null) {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qcontinuetrack), true, 2, this).show();
            return;
        }
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qnewtrack), true, 0, this).show();
    }

    private void onThisNavitrackreturnback() {
        //当前航迹返程，保存当前航迹。
        if (DBDataCenter.getInstance().wayTrailThis == null || DBDataCenter.getInstance().wayTrailThis.trackPointList == null) {
            showShortToast(getString(R.string.tnotrack));
            return;
        }

        if (DBDataCenter.getInstance().wayTrailThis.trackPointList.size() < 3) {
            showShortToast(getString(R.string.navitrackmap_navi));
            return;
        }

        if (Start.getInstance().isHavePath()) {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qsavetrack_return_havepath), true, 33, this).show();
        } else {
            new AlertDialog(context, getString(R.string.wxts), getString(R.string.qsavetrack_return), true, 33, this).show();
        }

    }

    private void onPauseRec() {
        if (DBDataCenter.getInstance().wayTrailThis == null) {
            showShortToast(getString(R.string.nothistrack));
            return;
        }
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qpausetrack), true, 1, this).show();
    }

    private void onCloseRec() {
        if (DBDataCenter.getInstance().wayTrailThis == null) {
            showShortToast(getString(R.string.tnotrack));
            return;
        }
        new AlertDialog(context, getString(R.string.wxts), getString(R.string.qsavetrack), true, 3, this).show();
    }

    private void onInitRec() {
        if (DBDataCenter.getInstance().wayTrailThis != null) {
            if (DBDataCenter.getInstance().wayTrailThis.getIsPause()) {
                doRec(0);
            } else {
                doRec(1);
            }
        } else {
            doRec(-1);
        }
    }

    int mRecState = -2;//航迹记录状态 -1-关闭  0-暂停 1-记录中

    private void doRec(int state) {
        if (Utils.isFastDoubleClick())
            return;

        if (mRecState == state) {
            return;
        }
        ibt_rec_begin.setBackgroundResource(R.drawable.btn_rec11);

        mRecState = state;
        switch (mRecState) {
            default:
                break;
            case 0:
                ibt_rec_begin.setVisibility(View.VISIBLE);
                ibt_rec_pause.setVisibility(View.GONE);
                ibt_rec_stop.setVisibility(View.VISIBLE);
                tv_navitrackreturnback.setVisibility(View.VISIBLE);
                break;
            case 1:
//                ibt_rec_begin.setBackgroundResource(R.drawable.btn_rec);
//                ibt_rec_begin.setVisibility(View.VISIBLE);
                ibt_rec_begin.setVisibility(View.GONE);
                ibt_rec_pause.setVisibility(View.VISIBLE);
                ibt_rec_stop.setVisibility(View.VISIBLE);
                tv_navitrackreturnback.setVisibility(View.VISIBLE);
                break;
            case -1:
                DBDataCenter.getInstance().wayTrailThis = null;
                ibt_rec_begin.setVisibility(View.VISIBLE);
                ibt_rec_pause.setVisibility(View.GONE);
                ibt_rec_stop.setVisibility(View.GONE);
                tv_navitrackreturnback.setVisibility(View.GONE);
                SysUtils.getInstance().saveWaytrailID(0L);
                break;
        }
    }

    void closeAllPath() {
        Start.getInstance().MapKit().clearRoute();
        Start.getInstance().MapKit().clearNavStart();
        Start.getInstance().MapKit().mNavDest = null;
        Start.getInstance().setHavePath(false);
        DBDataCenter.getInstance().makerNavi = null;
        mNaviInfoView.setHavepath(Start.getInstance().isHavePath());
        overNavibtn.setVisibility(View.GONE);
        naviLineOver();
        wayTrailNaviOver();
        _routeline = null;

        _routeline = null;
        _routelineH = null;

        if (_routelineMapsforge != null) {
            mMultiMapView.mapView.getLayerManager().getLayers().remove(_routelineMapsforge);
            _routelineMapsforge.getLatLongs().clear();
        }

        //重置路径相关的行程信息
        TripDataFileHandle.getInstance().mTripDatainfo.setPianhz(0);//偏航距
        TripDataFileHandle.getInstance().mTripDatainfo.setFhhx(-1);
        TripDataFileHandle.getInstance().mTripDatainfo.setRemainDistance(0);

        TripDataFileHandle.getInstance().mTripDatainfo.setDqmb(null);
        TripDataFileHandle.getInstance().mTripDatainfo.setDqjl(-1);

        SystemAllInfo sInfo = SystemCenter.getInstance().getSysInfo("HistoryData2");
        if (sInfo != null) {
            sInfo.setContent("");
            SystemCenter.getInstance().saveSysInfo(sInfo);
        }

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {

        if (requestCode == 1111) {
            doAddMarker(isPositive);
            return;
        }

        if (isPositive == false) {
            return;
        }

        if (requestCode == 0) {
            //开启航迹
            DBDataCenter.getInstance().startThisWayTrail();
            doRec(1);
        } else if (requestCode == 1) {
            //暂停航迹
            DBDataCenter.getInstance().pauseThisWayTrail(true);
            doRec(0);
        } else if (requestCode == 2) {
            //暂停结束，恢复记录航迹
            DBDataCenter.getInstance().pauseThisWayTrail(false);
            doRec(1);
        } else if (requestCode == 3) {
            //close save航迹
            ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().wayTrailThis.trackPointList;
            if (trackPointList == null || trackPointList.size() < 5) {
                showShortToast(getString(R.string.tsavetrack));
                DBDataCenter.getInstance().closeThisWayTrail();
                doRec(-1);
                return;
            }

            editName(true, false);

        } else if (requestCode == 6) {

            editName(true, true);

        } else if (requestCode == 10) {
            closeAllPath();
            initWnd(MOVING_MODE);
        } else if (requestCode == 11) {
            naviLineOver();
            wayTrailNaviOver();
            NavFrameSDK.POIDescription data = mTipInfo.getData();
            if (data == null) {
                return;
            }

            LonLat llDest = Utils.wgs84togcj02(mTipInfo.getLL().GetLon(), mTipInfo.getLL().GetLat());//Utils GPS to 火星坐标

            Start.getInstance().MapKit().mNavDest = new NavFrameSDK.NavDest[1];
            Start.getInstance().MapKit().mNavDest[0] = NavFrameSDK.getInstance().new NavDest();
            Start.getInstance().MapKit().mNavDest[0].pos.lon = llDest.GetLon();
            Start.getInstance().MapKit().mNavDest[0].pos.lat = llDest.GetLat();
            Start.getInstance().MapKit().mNavDest[0].name = data.name;
            Start.getInstance().MapKit().mNavDest[0].eid = 0;

            Start.getInstance().MapKit().clearNavStart();
            mHandler.sendEmptyMessage(Msg.BEGINROUTE);
        } else if (requestCode == 60) {
            //保存测量记录
            int size = Start.getInstance().mMeasurelist.size();
            if (size < 2) {
                showShortToast(getString(R.string.savemesureerr));
                return;
            }

            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                    , getString(R.string.mesurename), SysUtils.getInstance().getTimeStr(System.currentTimeMillis()));
            toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO, false);
        } else if (requestCode == 30) {
            //继续航线导航
            naviLineNext();
        } else if (requestCode == 98) {
            overNavi();
            naviLineOver();
        } else if (requestCode == 99) {
            wayTrailNaviOver();
        } else if (requestCode == 33) {
            //close save航迹
            ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().wayTrailThis.trackPointList;
            if (trackPointList == null || trackPointList.size() < 3) {
                showShortToast(getString(R.string.tsavetrack));
                DBDataCenter.getInstance().closeThisWayTrail();
                doRec(-1);
                return;
            }

            closeAllPath();
            //如果不保存当前航迹就返程导航，就会有冲突，返程的按钮就一直可以点击。
//            doRec(0);
            showProgressDialog(R.string.loading);
            runThread(TAG + "initData", new Runnable() {
                @Override
                public void run() {
                    DBDataCenter.getInstance().wayTrailEdit = DBDataCenter.getInstance().wayTrailThis;
                    final boolean saveOk = DBDataCenter.getInstance().closeThisWayTrail();
                    runUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                            WayTrail wt = DBDataCenter.getInstance().wayTrailEdit;
                            DBDataCenter.getInstance().wayTrailNavi = new WayTrail();
                            DBDataCenter.getInstance().wayTrailNavi.clone(DBDataCenter.getInstance().reUpdateWayTrail(wt));
                            DBDataCenter.getInstance().wayTrailNavi.isReverse = true;
                            DBDataCenter.getInstance().wayTrailNavi.setIsshow(true);
                            naviByNavitrack();

                            //重新开启航迹
                            DBDataCenter.getInstance().startThisWayTrail();
                            doRec(1);
                            //matchpos里就可以导航。
                            updateMapView();
                        }
                    });
                }
            });

        } else if (requestCode == 2222) {
            onTipman();
        }
    }

    private void saveNaviLine(String linename) {
        long id = DBDataCenter.getInstance().addNewRoute();
        Route route = DBDataCenter.getInstance().getRouteById(id);
        String strWps = "";
        if (id > 0) {
            int i = 1;
            for (LonLat ll : Start.getInstance().mMeasurelist) {
                String name = linename + "-" + i;
                WayPoint wp = new WayPoint(name, ll);
                wp.setRouteid(id);
                Long wpId = DBDataCenter.getInstance().saveWayPoint(wp);
                wp.setId(wpId);
                if (strWps.length() < 1) {
                    strWps = wp.getId() + "";
                } else {
                    strWps += "-" + wp.getId();
                }
                i++;
            }
            route.setWaypoint(strWps);
            route.setName(linename);
            DBDataCenter.getInstance().saveRoute(route);
            showShortToast(getString(R.string.drawlineok));
        }

        setMeasureMode(0);
    }

    private void saveThisWayTrail(String name) {
        DBDataCenter.getInstance().wayTrailThis.setName(name);

        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                final boolean saveOk = DBDataCenter.getInstance().closeThisWayTrail();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        if (saveOk) {
                            showShortToast(getString(R.string.hjybc));
                        }
                        doRec(-1);
                    }
                });
            }
        });
    }

    private void editName(boolean toWindow, boolean isLine) {

        String name = "";
        if (isLine) {
            name = getString(R.string.drawline) + " " + new DecimalFormat("00").format(DBDataCenter.getInstance().getRouteList().size());
        } else {
            name = DBDataCenter.getInstance().wayTrailThis.getName();
            if (name.trim().length() < 1) {
                name = SysUtils.getInstance().getTimeStr(System.currentTimeMillis());
            }
        }

        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NICK
                    , getString(R.string.hjmc), StringUtil.getTrimedString(name), context.getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                    , getString(R.string.hjmc), StringUtil.getTrimedString(name));
        }

        if (isLine) {
            toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO4, !toWindow);
        } else {
            toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO3, !toWindow);
        }

    }

    private final int REQUEST_TO_SEARCH = 32;
    private final int REQUEST_TO_EDIT_TEXT_INFO = 23;
    private final int REQUEST_TO_EDIT_TEXT_INFO2 = 24;
    private final int REQUEST_TO_EDIT_TEXT_INFO3 = 34;
    private final int REQUEST_TO_EDIT_TEXT_INFO4 = 35;

    private final int REQUEST_TO_MEASUREINFO = 20001;

    private final int REQUEST_TO_MARKER = 66;
    private final int REQUEST_TO_MAPSET = 8888;

    boolean isAddmark = false;//从航点加入页面返回

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (Start.getInstance().MapKit().mGIS == 0) {
            System.exit(0);
        }

        if (requestCode == REQUEST_TO_MAPSET) {
            mMultiMapView.isgcj02 = MapSetInfo.getInstance().isgcj02();
        }
        if (requestCode == REQUEST_TO_MARKER) {
            isAddmark = true;
            return;
        }

        if (requestCode == REQUEST_TO_MEASUREINFO) {
            setMeasureMode(0);
            return;
        }

        if (requestCode == REQUEST_TO_SEARCH) {
            if (resultCode == Msg.SEACHSELECTEDONE) {
                if (DBDataCenter.getInstance().makerSeach != null) {
                    WayPoint wp = DBDataCenter.getInstance().makerSeach;
                    NavFrameSDK.POIDescription poiData = NavFrameSDK.getInstance().new POIDescription();
                    poiData.name = wp.getName();
                    poiData.position.lon = wp.getLL().GetLon();
                    poiData.position.lat = wp.getLL().GetLat();
                    mMultiMapView.setMapCenter(wp.getLL());
                    mMultiMapView.setScale(100000);
                    mTipInfo.setData(poiData);
                    DBDataCenter.getInstance().makerSeach = null;
                    LonLat llB = mMultiMapView.getMapCenter();
                    _tipPoint = mMultiMapView.LL2XY(llB);
                    updateMapView();
                }
                return;
            }
        }

        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_SEARCH:
                showPOIInfo(resultCode);
                updateMapView();
                break;
            case REQUEST_TO_EDIT_TEXT_INFO:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    measureSave(name);
                }
                break;
            case REQUEST_TO_EDIT_TEXT_INFO2:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    measureSaveRt(name);
                }
                break;
            case REQUEST_TO_EDIT_TEXT_INFO3:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    saveThisWayTrail(name);
                }
                break;
            case REQUEST_TO_EDIT_TEXT_INFO4:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    saveNaviLine(name);
                }
                break;
        }
    }

    private void showPOIInfo(int pos) {
        if (pos < 0 || pos >= Start.getInstance().MapKit().mPOIResult.size())
            return;

        NavFrameSDK.POIDescription poiData = Start.getInstance().MapKit().mPOIResult.get(pos);
        String tipname = poiData.name;
        if (tipname.length() > 1) {
            tipname = tipname.replace("*", " ");
        }
        mTipInfo.setText(tipname);
    }

    //<---route
    private int mRouteEcode = -1;
    private boolean mIsRouting = false;

    private void onRoute() {
        removeTip();
        mTipInfo.setVisibility(View.GONE);
        mTipInfo.setData(null);

        if (mIsRouting) {
            return;
        }
        mNaviInfoView.setHavepath(false);

        if (SysUtils.getInstance().navi_mode1 == 0) {
            beginRoute();
            mHandler.sendEmptyMessage(Msg.FINISHROUTE);
            return;
        }

        if (!Start.getInstance().haveMaps) {
            showShortToast(getString(R.string.dhsbqjzzgdt));
            return;
        }


        mPB = new ProgressDialog(getContext());
        mPB.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mPB.setMessage(getString(R.string.navi_routing_progress));
        mPB.setCancelable(false);
        mPB.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface arg0) {
            }
        });

        mPB.setMax(100);
        mPB.setProgress(0);
        mPB.show();

        mIsRouting = true;
        new Thread() {
            @Override
            public void run() {
                beginRoute();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mHandler.sendEmptyMessage(Msg.FINISHROUTE);
            }
        }.start();

        Timer processTimer = new Timer();
        processTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                int process = Start.getInstance().MapKit().getRoutingProcess();
                if (mPB != null) {
                    mPB.setProgress(process);
                } else {
                    cancel();
                }
            }
        }, 500, 500);
    }

    private void beginRoute() {
        mRouteEcode = -1;
        Start.getInstance().MapKit().clearRoute();
        if (Start.getInstance().MapKit().mNavDest == null
                || Start.getInstance().MapKit().mNavDest.length < 1) {
            return;
        }

        mIsRouting = true;
        Start.getInstance().setHavePath(false);

        String strDest = Start.getInstance().MapKit().mNavDest[0].name.trim();
        if (strDest.length() < 1) {
            LonLat ll = new LonLat(Start.getInstance().MapKit().mNavDest[0].pos.lon, Start.getInstance().MapKit().mNavDest[0].pos.lat);
            strDest = Utils.getLLStr(ll, 2);
            Start.getInstance().MapKit().mNavDest[0].name = strDest;
        }

        if (Start.getInstance().MapKit().mNavStart.pos.lon == 0) {
            LonLat carLL = SysUtils.getInstance().getLL();
            carLL = Utils.wgs84togcj02(carLL.GetLon(), carLL.GetLat());//Utils GPS to 火星坐标
            Start.getInstance().MapKit().mNavStart.pos.lon = carLL.GetLon();
            Start.getInstance().MapKit().mNavStart.pos.lat = carLL.GetLat();
            Start.getInstance().MapKit().mNavStart.pname = 0;
            Start.getInstance().MapKit().mNavStart.name = "";
            Start.getInstance().MapKit().mNavStart.dir = -1;
        }

        for (int i = 0; i < Start.getInstance().MapKit().mNavDest.length; i++) {
            HistoryData2 his = new HistoryData2();
            his.llo = Start.getInstance().MapKit().mNavDest[i].pos.lon;
            his.lla = Start.getInstance().MapKit().mNavDest[i].pos.lat;
            his.name = Start.getInstance().MapKit().mNavDest[i].name;
//            HistoryFileHandle.getInstance().add(his);

            String strHistoryData = JSON.toJSONString(his);
//            HistoryData2 historyData = JSON.parseObject(strHistoryData, HistoryData2.class);
            SystemAllInfo sInfo = SystemCenter.getInstance().getSysInfo("HistoryData2");
            if (sInfo == null) {
                sInfo = new SystemAllInfo(null, "HistoryData2", strHistoryData);
            } else {
                sInfo.setContent(strHistoryData);
            }
            SystemCenter.getInstance().saveSysInfo(sInfo);
            break;
        }

        if (SysUtils.getInstance().navi_mode1 == 0) {
            mRouteEcode = 0;
            return;
        }

        if (SysUtils.getInstance().navi_mode2 == 0) {
            Start.getInstance().MapKit().setCarRouteOption();
        } else {
            Start.getInstance().MapKit().setWalkRouteOption();
        }

        try {
            mRouteEcode = Start.getInstance().MapKit().route(Start.getInstance().MapKit().mNavStart,
                    Start.getInstance().MapKit().mNavDest, null);
            noTurnLimitMode = false;
            if (mRouteEcode == 113 && SysUtils.getInstance().navi_mode2 == 0) {
                if (Start.getInstance().MapKit().isCarRouteOption()) {
                    noTurnLimitMode = true;
                    Start.getInstance().MapKit().setCarRouteOptionNoLimit();
                    mRouteEcode = Start.getInstance().MapKit().route(Start.getInstance().MapKit().mNavStart,
                            Start.getInstance().MapKit().mNavDest, null);
                }

            }
        } catch (Exception e) {
            mRouteEcode = -600;
        }
    }

    private boolean noTurnLimitMode = false;
    private ProgressDialog mPB = null;

    private void onFinishRoute() {
        mIsRouting = false;
        if (mPB != null) {
            mPB.dismiss();
            mPB = null;
        }

        mIsRouting = false;

        if (mRouteEcode == 0 || mRouteEcode == 110 || mRouteEcode == 111) {
            Start.getInstance().setHavePath(true);
            try {
                LonLat LLA = new LonLat(Start.getInstance().MapKit().mNavStart.pos.lon, Start.getInstance().MapKit().mNavStart.pos.lat);
                LonLat LLB = new LonLat(Start.getInstance().MapKit().mNavDest[0].pos.lon, Start.getInstance().MapKit().mNavDest[0].pos.lat);
                LonLat LLC = SysUtils.getInstance().getLL();//车
                LLC = Utils.wgs84togcj02(LLC.GetLon(), LLC.GetLat());
                //初始设置偏航距
                double distanceToDest = Start.getInstance().MapKit().getDistance(LLB, LLC);
                double pianhz = Utils.pointToLineLL(LLA, LLB, LLC);
                TripDataFileHandle.getInstance().mTripDatainfo.setPianhz(pianhz);
                if (pianhz > 50) {
                    //设置返航角
                    double fhhx = Start.getInstance().MapKit().getDirection3(LLC, LLB);
                    TripDataFileHandle.getInstance().mTripDatainfo.setFhhx(fhhx);
                } else {
                    TripDataFileHandle.getInstance().mTripDatainfo.setFhhx(0);
                }
                TripDataFileHandle.getInstance().mTripDatainfo.setRemainDistance(distanceToDest);

                if (mRouteEcode == 0 && Start.getInstance().MapKit().prepareTurnAndGuid()) {
                    NavFrameSDK.TurnInfo turnInfo = NavFrameSDK.getInstance().new TurnInfo();
                    NavFrameSDK.GuideInfo guidInfo = NavFrameSDK.getInstance().new GuideInfo();
                    NavFrameSDK.CLonLat pPos = NavFrameSDK.getInstance().new CLonLat();
                    if (Start.getInstance().MapKit().nextTurnAndGuid(turnInfo, guidInfo, pPos)) {
                        TripDataFileHandle.getInstance().mTripDatainfo.setRemainDistance(guidInfo.remainDistance);
                    }
                    Start.getInstance().MapKit().finishTurnAndGuid();

                    NavFrameSDK.NavInfo navInfo = NavFrameSDK.getInstance().new NavInfo();
                    navInfo.guidInfo = guidInfo;
                    navInfo.turnInfo = turnInfo;
                    mNaviInfoView.setHavepath(true);
                    NavFrameSDK.NavPosition navpos = NavFrameSDK.getInstance().new NavPosition();
                    navpos.pos.lon = SysUtils.getInstance().getLL().GetLon();
                    navpos.pos.lat = SysUtils.getInstance().getLL().GetLat();
                    mNaviInfoView.setNavInfo(navInfo, navpos);

                    if (SysUtils.getInstance().navi_mode1 == 1) {
                        //当前目标
                        TripDataFileHandle.getInstance().mTripDatainfo.setDqmb(navInfo.turnInfo.toRoadName);
                        //当前距离
                        TripDataFileHandle.getInstance().mTripDatainfo.setDqjl(navInfo.guidInfo.distanceToTurn);
                    }

                }
            } catch (Exception e) {
            }

        } else {
            Start.getInstance().MapKit().clearRoute();
            Start.getInstance().MapKit().mNavDest = null;
            String strErr = getString(R.string.path_calculation_fails);
            switch (mRouteEcode) {
                case 110: // ERR_ROUTE_ORIGIN_INVALID
                    strErr += getString(R.string.route_errcode_1);
                    break;
                case 111: // ERR_ROUTE_DEST_INVALID
                    strErr += getString(R.string.route_errcode_2);
                    break;
                case 112: // ERR_ROUTE_DEST_ORIGIN_CLOSE
                    strErr += getString(R.string.route_errcode_3);
                    break;
            }

            Start.getInstance().setHavePath(false);
            mNaviInfoView.setHavepath(false);
            mMapMode = -1;
            initWnd(NAVI_MODE);
            Toast.makeText(getContext(), strErr, Toast.LENGTH_SHORT).show();

            if (_isNaviByRoute) {
                mHandler.sendEmptyMessage(Msg.NAVILINENEXT);
                return;
            }
        }

        Start.getInstance().MapKit().showFullPath();
        addRoute2MapMapsforge();
        addRoute2Map();

//        mHandler.sendEmptyMessage(Msg.UPDATEMAP);
        onLocal();
    }

    //route-->
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    private boolean mRegisteredSensor;
    private SensorManager mSensorManager;
    private float mSensorDegree = -1;

    private float[] mGData = new float[3];
    private float[] mMData = new float[3];
    private float[] mR = new float[16];
    private float[] mOrientation = new float[3];
    private int mCount;

    // 当传感器在被改变时触发
    @SuppressWarnings("deprecation")
    @Override
    public void onSensorChanged(SensorEvent event) {
        // 接受方向感应器的类型
        int type = event.sensor.getType();
        float[] data = null;
        if (type == Sensor.TYPE_ACCELEROMETER) {
            data = mGData;
        } else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
            data = mMData;
        }

        if (data != null) {
            for (int i = 0; i < 3; i++)
                data[i] = event.values[i];

            if (!SensorManager.getRotationMatrix(mR, null, mGData, mMData)) {
                return;
            }

            SensorManager.getOrientation(mR, mOrientation);
            float degree = -1;
            if (mCount++ > 50) {
                final float rad2deg = (float) (180.0f / Math.PI);
                mCount = 0;
                degree = (float) ((360f + mOrientation[0] * rad2deg) % 360);
            }

            if (degree > 0 && Math.abs(mSensorDegree - degree) > 10) {
                mSensorDegree = degree;
                Point e = mCar.getCarPos();
                if (e.x > 0 && e.x < 400 && e.y > 0 && e.y < 800) {
                    if (mMapMode == MOVING_MODE) {
                        mCar.setCarHeading(mSensorDegree);
                        mHandler.sendEmptyMessage(Msg.UPDATEMAP);
//                    } else if (CourseInfo.getInstance().isUseGpsdir(GPSProvider.getInstance().getSpeed() * 3.6f)) {
                    } else if (GPSProvider.getInstance().getSpeed() * 3.6 < 1 && !Start.getInstance().isHavePath()) {
                        mCar.setCarHeading(mSensorDegree);
                        if (mCar.getCarposMode() == Car.BOTTOMCENTER) {
                            mMultiMapView.setMapOrientation((float) mCar.navpos_.dir);
                        }
                        mHandler.sendEmptyMessage(Msg.UPDATEMAP);
                    }
                }
            }
        } else if (type == Sensor.TYPE_PRESSURE) {
            float sPV = event.values[0];//hPa-百帕==毫巴
            QiyaCenter.getInstance().saveQiyaInfo(new QiyaInfo(sPV));//百帕
            TripDataFileHandle.getInstance().mTripDatainfo.setQiya(sPV * 100);//帕
        } else if (type == Sensor.TYPE_TEMPERATURE) {
            mWendu = event.values[0];//°C
            TripDataFileHandle.getInstance().mTripDatainfo.setWendu(mWendu);//传入的是传感器的温度
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }


    public void naviByRoute() {
        tv_navilineclose.setVisibility(View.GONE);

        if (DBDataCenter.getInstance().routeNavi == null || DBDataCenter.getInstance().routeNavi.waypointList == null) {
            _isNaviByRoute = false;
            return;
        }

        Route routeNavi = DBDataCenter.getInstance().routeNavi;
        int size = routeNavi.waypointList.size();
        if (size < 1) {
            _isNaviByRoute = false;
            DBDataCenter.getInstance().routeNavi = null;
            return;
        }

        //设置完整航线的地图中心点和比例尺
//        DBDataCenter.getInstance().showFullRoute(DBDataCenter.getInstance().routeNavi.waypointList);
//        updateMapView();
        _isNaviByRoute = true;
//        tv_navilineclose.setVisibility(View.VISIBLE);
        int destIndex = DBDataCenter.getInstance().routeNaviIndex;
        if (Start.getInstance().isHavePath()) {
            //已经在导航
        } else if (destIndex <= size - 1) {
            naviLineNext();
        } else {
            naviLineOver();
        }
    }

    public void naviLineOver() {
        DBDataCenter.getInstance().routeNavi = null;
        DBDataCenter.getInstance().routeNaviIndex = 0;
        _isNaviByRoute = false;
        tv_navilineclose.setVisibility(View.GONE);
        updateMapView();
    }

    public void wayTrailNaviOver() {
        DBDataCenter.getInstance().wayTrailNavi = null;
        tv_navitrackclose.setVisibility(View.GONE);
        updateMapView();
    }

    //导航到航线目的地
    public void naviLineNext() {
        if (DBDataCenter.getInstance().routeNavi == null
                || DBDataCenter.getInstance().routeNavi.waypointList == null
                || DBDataCenter.getInstance().routeNavi.waypointList.size() < 1) {
            _isNaviByRoute = false;
            return;
        }

        int destIndex = DBDataCenter.getInstance().routeNaviIndex;
        int size = DBDataCenter.getInstance().routeNavi.waypointList.size();
        int j = destIndex;
        if (destIndex >= size) {
            j = size - 1;
        }
//        Start.getInstance().MapKit().mNavDest = new NavFrameSDK.NavDest[size - destIndex];
//
//        for (int i = destIndex; i < size; i++) {
//            WayPoint wp = DBDataCenter.getInstance().routeNavi.waypointList.get(i);
//            LonLat llDest = Utils.wgs84togcj02(wp.getLL().GetLon(), wp.getLL().GetLat());//Utils GPS to 火星坐标
//            Start.getInstance().MapKit().mNavDest[j] = NavFrameSDK.getInstance().new NavDest();
//            Start.getInstance().MapKit().mNavDest[j].pos.lon = llDest.GetLon();
//            Start.getInstance().MapKit().mNavDest[j].pos.lat = llDest.GetLat();
//            Start.getInstance().MapKit().mNavDest[j].name = wp.getName();
//            Start.getInstance().MapKit().mNavDest[j].eid = 0;
//            j++;
//        }
        //航线导航不能多目的地原因：1.航点超过10个；2.两个航点的间距太多一段算不出来会导致整段算不出来
        Start.getInstance().MapKit().mNavDest = new NavFrameSDK.NavDest[1];
        WayPoint wp = DBDataCenter.getInstance().routeNavi.waypointList.get(destIndex);
        LonLat llDest = Utils.wgs84togcj02(wp.getLL().GetLon(), wp.getLL().GetLat());//Utils GPS to 火星坐标
        Start.getInstance().MapKit().mNavDest[0] = NavFrameSDK.getInstance().new NavDest();
        Start.getInstance().MapKit().mNavDest[0].pos.lon = llDest.GetLon();
        Start.getInstance().MapKit().mNavDest[0].pos.lat = llDest.GetLat();
        Start.getInstance().MapKit().mNavDest[0].name = wp.getName();
        Start.getInstance().MapKit().mNavDest[0].eid = 0;

        Start.getInstance().MapKit().clearNavStart();
        mHandler.sendEmptyMessage(Msg.BEGINROUTE);
    }

    public void onNextNaviLine() {
        if (DBDataCenter.getInstance().routeNavi == null || DBDataCenter.getInstance().routeNavi.waypointList == null) {
            _isNaviByRoute = false;
            return;
        }
        int destIndex = DBDataCenter.getInstance().routeNaviIndex;
        WayPoint wpA = DBDataCenter.getInstance().routeNavi.waypointList.get(destIndex);
        destIndex++;
        int size = DBDataCenter.getInstance().routeNavi.waypointList.size();
        if (destIndex >= size) {
//            naviLineOver();
//            new zuo.biao.library.ui.AlertDialog(context, "", "已到达航线最终目的地，结束航线导航！", false, 31, this).show();
            closeAllPath();
            showShortToast(getString(R.string.navidest));
            return;
        }
        DBDataCenter.getInstance().routeNaviIndex++;
        WayPoint wpB = DBDataCenter.getInstance().routeNavi.waypointList.get(destIndex);
        String strMsg = getString(R.string.tlinedest0) + wpA.getName() + "\n" +getString(R.string.tlinedest1) + wpB.getName();
        showShortToast(strMsg);
//        new zuo.biao.library.ui.AlertDialog(context, "", strMsg, false, 30, this).show();
        naviLineNext();

    }

    public void naviToNavipt() {
        if (DBDataCenter.getInstance().makerNavi == null) {
            return;
        }

        LonLat destLL = DBDataCenter.getInstance().makerNavi.getLL();
        destLL = Utils.wgs84togcj02(destLL.GetLon(), destLL.GetLat());//Utils GPS to 火星坐标
        String name = DBDataCenter.getInstance().makerNavi.getName();
        DBDataCenter.getInstance().makerNavi = null;

        Start.getInstance().MapKit().mNavDest = new NavFrameSDK.NavDest[1];
        Start.getInstance().MapKit().mNavDest[0] = NavFrameSDK.getInstance().new NavDest();
        Start.getInstance().MapKit().mNavDest[0].pos.lon = destLL.GetLon();
        Start.getInstance().MapKit().mNavDest[0].pos.lat = destLL.GetLat();
        Start.getInstance().MapKit().mNavDest[0].name = name;
        Start.getInstance().MapKit().mNavDest[0].eid = 0;

        Start.getInstance().MapKit().clearNavStart();
        mHandler.sendEmptyMessage(Msg.BEGINROUTE);
    }


    // 地图引擎 图层+操作回调
    void removeTip() {
        _tipPoint = null;
        mTipInfo.setVisibility(View.GONE);
        mTipInfo.setData(null);
    }

    //航线导航的航点
    boolean _isNaviByRoute = false;
    Car mCar = new Car();

    int mMeasureMode = 0;//测量模式 0--正常模式 1-测距 2-面积测量 3--画航线

    //重新查询大头针的信息
    void resetTipInfo() {
        if (_tipPoint == null) {
            return;
        }

        Point point = new Point();
        point.set((int) (_tipPoint.x / mMultiMapView.mMapViewS._ws), (int) (_tipPoint.y / mMultiMapView.mMapViewS._ws));
        LonLat tipLL = Start.getInstance().MapKit().XY2LL(point);
        if (tipLL == null) {
            return;
        }

        LonLat tipLLB = Utils.gcj02towgs84(tipLL.GetLon(), tipLL.GetLat());//Utils 火星坐标 to GPS
        //40x40范围内如果有航点，则显示航点信息
        //找到航点的最小矩形范围
        WayPoint wp = DBDataCenter.getInstance().getNearWaypt(tipLLB);
        DBDataCenter.getInstance().makerEdit = wp;
        if (wp == null) {
            //5米以内的poi
            Start.getInstance().MapKit().mTipPoiList = Start.getInstance().MapKit()
                    .getNearPoi(tipLL, true);
            if (Start.getInstance().MapKit().mTipPoiList.size() > 0) {
                NavFrameSDK.POIDescription data = Start.getInstance().MapKit().mTipPoiList.get(0);
                mTipInfo.showBtn();//是否显示两边的按钮
                mTipInfo.setData(data);
            }
        } else {
            mTipInfo.setText(wp.getName());
        }

        mTipInfo.setLL(tipLLB);
        if (mHandler != null) {
            mHandler.sendEmptyMessage(Msg.CHANGEMAPINFO);
        }

        mMultiMapView.updateMap();
    }

    Point _tipPoint = null;

    void onChangeTile() {

        LonLat ll = mMultiMapView.getMapCenter();
        if (mMultiMapView.isgcj02) {
            ll = Utils.gcj02towgs84(ll.GetLon(), ll.GetLat());//Utils GPS to 火星坐标
        }

        SysUtils.getInstance().mapsource++;
        if (SysUtils.getInstance().mapsource == 4) {
            SysUtils.getInstance().mapsource = 1000;
        } else if (SysUtils.getInstance().mapsource == 1001) {
            if (!SysUtils.getInstance().mapsforgeFile.exists()) {
                SysUtils.getInstance().mapsource++;
            }
        }

        if (SysUtils.getInstance().mapsource == 1002) {
            File osmFile = new File(SysUtils.getInstance().mapfilepath2);
            if (!osmFile.exists()) {
                SysUtils.getInstance().mapsource++;
            }
        }

        if (SysUtils.getInstance().mapsource > 1002) {
            SysUtils.getInstance().mapsource = 0;
        }

        SysUtils.getInstance().saveMapSource();
        onChangeMapsource(ll);
    }

    public void onChangeMapsource(LonLat ll) {

        mMultiMapView.setMapsource(SysUtils.getInstance().mapsource);

        int select = SysUtils.getInstance().mapsource;
        switch (select) {
            default:
                break;
            case 1000:
            case 1001:
            case 1002:
            case 1003:
            case 1004:
//                tv_tile.setVisibility(View.GONE);
                break;
        }

        tv_tile.setText(mMultiMapView.getMapsourceStr(select));

        if (ll != null) {
            mMultiMapView.setMapOrientation(0);
            mMultiMapView.setMapCenter(ll);
        }

        if (SysUtils.getInstance().mapsource == 1001) {
            //如果更换了数据文件，intMapsforge()，则必需重新加入图层;或者地图图层为第0层
//            mMultiMapView.mapView.getLayerManager().getLayers().remove(mapsforgeLayer);
//            mMultiMapView.mapView.getLayerManager().getLayers().add(mapsforgeLayer);
        }

        mMultiMapView.updateMap();
    }


    private void initMapEngin() {
        mGisOverlay = new CustomPointOverlay();
        mMultiMapView.mMapViewOnline.getOverlays().add(mGisOverlay);
        mMultiMapView.mapView.addLayer(mapsforgeLayer);

        mMultiMapView.setMapCallback(mCallback, mapListener);

        mMultiMapView.setMapCenter(SysUtils.getInstance().getLL());
        mMultiMapView.setScale(100000);

    }

    // ===============TME
    MapViewS.MapCallBack mCallback = new MapViewS.MapCallBack() {


        @Override
        public void drawOverlay(Canvas canvas, float ws) {

            if (mMultiMapView.getMapsource() != 1000) {
                return;
            }
            MapViewS mMapViewS = mMultiMapView.mMapViewS;

            MapSetInfo.getInstance().draw(getContext(), canvas, ws, mMapViewS);
            if (mMapMode == MOVING_MODE) {
                //当前位置到地图中心的连线
//            drawLineCar2Center(canvas, ws);
                drawLineCar2Tip(canvas, ws);
            }

            drawLineCar2dest(canvas, ws);//车到最终目的地的连线
            drawNavDest(canvas, ws);//目的地icon
            drawMeasure(canvas, ws);//测量

            drawMarker(canvas, ws);//显示航点

            if (_isNaviByRoute) {
                drawRoute(canvas, ws);//画航线
            }

            PaomaoInfo.getInstance().draw(getContext(), canvas, ws, mMapViewS);//画抛锚点

            TrackShow.getInstance().drawWayTrailAll(getContext(), canvas, ws, mMapViewS, null);

            if (SysUtils.getInstance()._realtimeArea != -1) {
                MeasureCenter.getInstance().drawmeasureRT(getContext(), canvas, ws, mMapViewS);
            }

            mCar.setMapsize(mMapViewS._mapWidth, mMapViewS._mapHeight);
            mCar.draw(getContext(), canvas, ws, ws);
//            mCompass.draw(getContext(), canvas, ws, ws);


//        SrtmService.getInstance().preDraw(canvas, mMapViewS.llRect, mMapViewS._mapWidth, mMapViewS._mapHeight, ws);

            //画完图
            if (mHandler != null) {
                mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);
            }

        }

        // 在地图上显示新增的icon--单击移图到地图中心并且弹出tipinfo（如果点击处有icon则地图中心做修正）
        @Override
        public void popTipInfo(NavFrameSDK.POIDescription data) {
            if (mMeasureMode > 0) {
                return;
            }

            //40x40范围内如果有航点，则显示航点信息
            //找到航点的最小矩形范围
            LonLat ll = mMultiMapView.getMapCenter();
            if (mMultiMapView.isgcj02) {
                ll = Utils.gcj02towgs84(ll.GetLon(), ll.GetLat());
            }
            WayPoint wp = DBDataCenter.getInstance().getNearWaypt(ll);
            if (wp != null) {
                DBDataCenter.getInstance().makerEdit = wp;
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(Msg.ADDMARKER);
                }

//            mTipInfo.setVisibility(View.GONE);
//            mTipInfo.setData(null);
                return;
            }

            mTipInfo.showBtn();//是否显示两边的按钮
            mTipInfo.setData(data);
            mTipInfo.setLL(ll);

            if (mHandler != null) {
                mHandler.sendEmptyMessage(Msg.CHANGEMAPINFO);
            }


        }

        // 移图进入移图模式
        @Override
        public void moveMap(boolean removeTip) {
            if (removeTip) {
//            mTipInfo.setVisibility(View.GONE);
            }

//                _auto2navimodeTime = 0;
            if (mMapMode == MOVING_MODE) {
                resetTipInfo();
                return;
            }
//                initWnd(MOVING_MODE);
            if (mHandler != null) {
                mHandler.sendEmptyMessage(Msg.TOMOVINGMODE);
            }
        }

        //长按不移图
        @Override
        public void longPress(LonLat ll) {
            if (mMeasureMode > 0) {
                return;
            }

            if (ll != null) {
                removeTip();
                ll = Utils.gcj02towgs84(ll.GetLon(), ll.GetLat());
                addMarkByLL(ll, null);
            }
        }

        //双击
        @Override
        public void doubleClick(LonLat ll) {
            if (mFHandler != null && mMeasureMode == 0) {
                mFHandler.sendEmptyMessage(Msg.DOAUTOTAB);
            }
        }

        //单击 单击后
        @Override
        public void singleClick(LonLat ll, Point tipPoint) {
            if (mMeasureMode > 0) {
                return;
            }

            if (mMapMode == NAVI_MODE) {
                initWnd(MOVING_MODE);
            }

            _tipPoint = tipPoint;
            resetTipInfo();
        }

        //移图后抬起
        @Override
        public void touchUp() {
//            if (mMapMode == MOVING_MODE) {
//                resetTipInfo();
//                return;
//            }
        }
    };

    private void addMark() {
        LonLat ll = mCar.getCarLL();
        String name = null;
        NavFrameSDK.POIDescription data = mTipInfo.getData();
        if (data != null) {
            ll = mTipInfo.getLL();
            name = data.name;
            Point A = mMultiMapView.LL2XY(ll);
            if (_tipPoint != null && mMultiMapView.getMapsource() == 1000) {
                Point point = new Point();
                point.set((int) (_tipPoint.x / mMultiMapView.mMapViewS._ws), (int) (_tipPoint.y / mMultiMapView.mMapViewS._ws));
                LonLat tipLL = Start.getInstance().MapKit().XY2LL(point);
                LonLat llp = Utils.gcj02towgs84(tipLL.GetLon(), tipLL.GetLat());
                double distance = Start.getInstance().MapKit().getDistance(ll, llp);
                if (distance > 5) {
                    ll = llp;
                    name = "";
                    Start.getInstance().MapKit().mTipPoiList = Start.getInstance().MapKit()
                            .getNearPoi(tipLL, true);
                    if (Start.getInstance().MapKit().mTipPoiList.size() > 0) {
                        NavFrameSDK.POIDescription data2 = Start.getInstance().MapKit().mTipPoiList.get(0);
                        name = data2.name;
                        mTipInfo.setData(data2);
                    }
                }
            }
        }

        addMarkByLL(ll, name);
    }

    private void addMarkByLL(LonLat ll, String name) {
        if (ll == null) {
            return;
        }
        if (name != null) {
            name = name.trim();
        }
        if (PoiCollectInfo.getInstance().getSavemode() == 0) {
            WayPoint wp = DBDataCenter.getInstance().createNewWayPoint(ll);
            if (name != null && name.length() > 2) {
                wp.setName(name);
            }
            if (mMapMode == NAVI_MODE || _tipPoint == null) {
                wp.setAltitude(GPSProvider.getInstance().getAltitude());
                if (QiyaCenter.getInstance()._thisQiyaInfo != null) {
                    double qiyaH = QiyaCenter.getInstance()._thisQiyaInfo.getAltitude();
                    double H = wp.getAltitude();
                    if (Math.abs((int) (qiyaH - H)) < 100 || H == 0) {
                        //气压高度误差太大；可能气压高度是不准确的则不用
                        wp.setAltitude(qiyaH);
                    }
                }
            }
            DBDataCenter.getInstance().saveWayPoint(wp);
            Toast.makeText(getContext(), getContext().getString(R.string.savenaviptok), Toast.LENGTH_SHORT).show();
            mMultiMapView.updateMap();
        } else {
            WayPoint wayPoint = DBDataCenter.getInstance().createNewWayPoint(ll);
            if (name != null && name.length() > 2) {
                wayPoint.setName(name);
            }
            DBDataCenter.getInstance().makerEdit = wayPoint;
            if (mMapMode == NAVI_MODE || _tipPoint == null) {
                DBDataCenter.getInstance().makerEdit.setAltitude(GPSProvider.getInstance().getAltitude());
                if (QiyaCenter.getInstance()._thisQiyaInfo != null) {
                    double qiyaH = QiyaCenter.getInstance()._thisQiyaInfo.getAltitude();
                    double H = DBDataCenter.getInstance().makerEdit.getAltitude();
                    if (Math.abs((int) (qiyaH - H)) < 100 || H == 0) {
                        //气压高度误差太大；可能气压高度是不准确的则不用
                        DBDataCenter.getInstance().makerEdit.setAltitude(qiyaH);
                    }
                }
            }
            if (mHandler != null) {
                mHandler.sendEmptyMessage(Msg.ADDMARKER);
            }
        }

    }

    //显示附加图层
    private void drawLineCar2Center(Canvas canvas, float ws) {
        if (mMeasureMode != 0) {
            return;
        }

        int w = mMultiMapView.mMapViewS._mapWidth;
        int h = mMultiMapView.mMapViewS._mapHeight;

        Point A = Start.getInstance().MapKit().LL2XY(Start.getInstance().MapKit().getMapCenter());

        LonLat ll = mCar.getCarLL();
        ll = Utils.wgs84togcj02(ll.GetLon(), ll.GetLat());//Utils GPS to 火星坐标
        Point B = Start.getInstance().MapKit().LL2XY(ll);
        int[] line = {A.x, A.y, B.x, B.y};
        Utils.revisePt(line, w, h);

        PathEffect pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
        Paint paint = new Paint();
        paint.reset();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(4);
        paint.setColor(Color.GRAY);
        paint.setAntiAlias(true);
        paint.setPathEffect(pathEffect);
        Path path = new Path();
        path.moveTo(line[0] * ws, line[1] * ws);
        path.lineTo(line[2] * ws, line[3] * ws);
        canvas.drawPath(path, paint);
    }

    private boolean _havepos = false;

    private void drawLineCar2Tip(Canvas canvas, float ws) {
        if (mMeasureMode != 0) {
            return;
        }
        //当前位置到tip的连线+大头针
        int w = mMultiMapView.mMapViewS._mapWidth;
        int h = mMultiMapView.mMapViewS._mapHeight;

        if (_tipPoint == null) {
            if (mHandler != null) {
                mHandler.sendEmptyMessage(Msg.CHANGEMAPINFO);
            }
            return;
        }
        Point A = _tipPoint;
        LonLat ll = mCar.getCarLL();
        ll = Utils.wgs84togcj02(ll.GetLon(), ll.GetLat());//Utils GPS to 火星坐标
        Point B = Start.getInstance().MapKit().LL2XY(ll);
        int[] line = {A.x, A.y, (int) (B.x * ws), (int) (B.y * ws)};
        Utils.revisePt(line, (int) (w * ws), (int) (h * ws));

        PathEffect pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
        Paint paint = new Paint();
        paint.reset();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(4);
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);
        paint.setPathEffect(pathEffect);
        Path path = new Path();
        path.moveTo(line[0], line[1]);
        path.lineTo(line[2], line[3]);
        canvas.drawPath(path, paint);

        Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.center_marker))
                .getBitmap();
        int x = (int) (line[0] - bm.getWidth());
        int y = (int) (line[1] - bm.getHeight());
        canvas.drawBitmap(bm, x, y, null);
    }

    private void drawLineCar2dest(Canvas canvas, float ws) {
        if (!Start.getInstance().isHavePath())
            return;

        if (Start.getInstance().MapKit().mNavDest == null || mCar == null) {
            return;
        }
        int size = Start.getInstance().MapKit().mNavDest.length;
        if (size < 1)
            return;

        int indexDest = size - 1;
        float[] ff = new float[4];
        LonLat destLL = new LonLat(
                Start.getInstance().MapKit().mNavDest[indexDest].pos.lon,
                Start.getInstance().MapKit().mNavDest[indexDest].pos.lat);

        Point d = Start.getInstance().MapKit().LL2XY(destLL);
        ff[0] = d.x * ws;
        ff[1] = d.y * ws;

        LonLat ll = mCar.getCarLL();
        ll = Utils.wgs84togcj02(ll.GetLon(), ll.GetLat());//Utils GPS to 火星坐标

        Point carpos = Start.getInstance().MapKit().LL2XY(ll);
        ff[2] = carpos.x * ws;
        ff[3] = carpos.y * ws;

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.RED);
        paint.setStrokeWidth((float) 3.0);
        canvas.drawLines(ff, paint);
    }

    private void drawNavDest(Canvas canvas, float ws) {
        if (!Start.getInstance().isHavePath())
            return;

        if (Start.getInstance().MapKit().mNavDest != null
                && Start.getInstance().MapKit().mNavDest.length > 0) {
            int count = Start.getInstance().MapKit().mNavDest.length;
            int resId = R.drawable.destination;
            for (int i = 0; i < count; ++i) {
                LonLat poiLL = new LonLat(
                        Start.getInstance().MapKit().mNavDest[i].pos.lon,
                        Start.getInstance().MapKit().mNavDest[i].pos.lat);

                if (!mMultiMapView.mMapViewS.isInMapRegion(poiLL)) {
                    continue;
                }
                Point e = Start.getInstance().MapKit().LL2XY(poiLL);
                int z = 1;
                if (i == count - 1) {
                    resId = R.drawable.destination;
                    z = 2;
                } else {
                    resId = R.drawable.marker01 + i;
                    if (resId > R.drawable.marker15) {
                        resId = R.drawable.marker15;
                    }
                }

                Bitmap bm = ((BitmapDrawable) getResources().getDrawable(resId))
                        .getBitmap();
                int x = (int) (e.x * ws - bm.getWidth() / 2);
                int y = (int) (e.y * ws - bm.getHeight() / z);
                canvas.drawBitmap(bm, x, y, null);
            }
        }
    }

    private void drawMeasure(Canvas canvas, float ws) {
        int count = Start.getInstance().mMeasurelist.size();
        if (count < 1) {
            return;
        }

        int w = mMultiMapView.mMapViewS._mapWidth;
        int h = mMultiMapView.mMapViewS._mapHeight;

        Paint paint = new Paint();
        paint.reset();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(4);
        paint.setColor(Color.parseColor("#AA0000FF"));
        paint.setAntiAlias(true);
        PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
        paint.setPathEffect(pathEffect);
        Path path = new Path();

        if (count >= 2) {
            Point AA = null;
            int ii = -1;
            for (int i = 1; i < count; ++i) {
                LonLat poiLLA = Start.getInstance().mMeasurelist.get(i - 1);
                LonLat poiLLB = Start.getInstance().mMeasurelist.get(i);

                poiLLA = Utils.wgs84togcj02(poiLLA.GetLon(), poiLLA.GetLat());//Utils GPS to 火星坐标
                poiLLB = Utils.wgs84togcj02(poiLLB.GetLon(), poiLLB.GetLat());//Utils GPS to 火星坐标

                double[] lineLL = {poiLLA.GetLon(), poiLLA.GetLat(), poiLLB.GetLon(), poiLLB.GetLat()};
                if (!Utils.isLineIntersectRectangle(mMultiMapView.mMapViewS.getMapRegion(), lineLL)) {
                    continue;
                }
                Point A = null;
                if (AA != null && ii == i - 1) {
                    A = AA;
                } else {
                    A = Start.getInstance().MapKit().LL2XY(poiLLA);//耗时操作能省则省
                }
                Point B = Start.getInstance().MapKit().LL2XY(poiLLB);
                AA = B;
                int[] line = {A.x, A.y, B.x, B.y};
                if (Utils.revisePt(line, w, h)) {
                    path.moveTo(line[0] * ws, line[1] * ws);
                    path.lineTo(line[2] * ws, line[3] * ws);
                }
            }

            if (mMeasureMode == 2) {
                //目前主地图不测面积，如需测面积需回复原画线方式
                path.close();//封闭
                paint.setColor(Color.LTGRAY);
            }

            canvas.drawPath(path, paint);

            if (mMeasureMode == 2) {
                paint.setColor(Color.parseColor("#AAFF0000"));
                paint.setStyle(Paint.Style.FILL);
                canvas.drawPath(path, paint);
            }
        }

        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(13);
        paint.setFakeBoldText(true);

        for (int i = 0; i < count; ++i) {
            LonLat poiLL = Start.getInstance().mMeasurelist.get(i);
            poiLL = Utils.wgs84togcj02(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
            if (i == count - 1 && _measureisgcj02 && _measureLL != null) {
                poiLL = _measureLL;
            }
            if (!mMultiMapView.mMapViewS.isInMapRegion(poiLL)) {
                continue;
            }
            paint.setColor(Color.parseColor("#AAFF0000"));
            Point ff = Start.getInstance().MapKit().LL2XY(poiLL);
            canvas.drawCircle(ff.x * ws, ff.y * ws, dip2px(12), paint);
            String strPrn = (i + 1) + "";
            float textWidth = paint.measureText(strPrn) / 2;
            float textHeight = paint.getTextSize() / 2;
            paint.setColor(Color.WHITE);
            canvas.drawText(strPrn, ff.x * ws - textWidth, ff.y * ws + textHeight - 1,
                    paint);
        }

    }

    private void drawRoute(Canvas canvas, float ws) {
        int w = mMultiMapView.mMapViewS._mapWidth;
        int h = mMultiMapView.mMapViewS._mapHeight;

        PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.parseColor("#AA0000FF"));
        paint.setStrokeWidth(4);
        paint.setAntiAlias(true);
        paint.setPathEffect(pathEffect);
        Path path = new Path();

        Point AA = null;
        int ii = -1;
        int count = DBDataCenter.getInstance().routeNavi.waypointList.size();
        for (int i = 1; i < count; ++i) {
            LonLat poiLLA = DBDataCenter.getInstance().routeNavi.waypointList.get(i - 1).getLL();
            LonLat poiLLB = DBDataCenter.getInstance().routeNavi.waypointList.get(i).getLL();

            poiLLA = Utils.wgs84togcj02(poiLLA.GetLon(), poiLLA.GetLat());//Utils GPS to 火星坐标
            poiLLB = Utils.wgs84togcj02(poiLLB.GetLon(), poiLLB.GetLat());//Utils GPS to 火星坐标

            double[] lineLL = {poiLLA.GetLon(), poiLLA.GetLat(), poiLLB.GetLon(), poiLLB.GetLat()};
            if (!Utils.isLineIntersectRectangle(mMultiMapView.mMapViewS.getMapRegion(), lineLL)) {
                continue;
            }

            Point A = null;
            if (AA != null && ii == i - 1) {
                A = AA;
            } else {
                A = Start.getInstance().MapKit().LL2XY(poiLLA);//耗时操作能省则省
            }
            Point B = Start.getInstance().MapKit().LL2XY(poiLLB);
            AA = B;
            ii = i;

            int[] line = {A.x, A.y, B.x, B.y};
            if (Utils.revisePt(line, w, h)) {
                path.moveTo(line[0] * ws, line[1] * ws);
                path.lineTo(line[2] * ws, line[3] * ws);
            }
        }

        canvas.drawPath(path, paint);

        //画icon
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(13);
        paint.setFakeBoldText(true);

        for (int i = 0; i < count; ++i) {
            LonLat poiLL = DBDataCenter.getInstance().routeNavi.waypointList.get(i).getLL();
            poiLL = Utils.wgs84togcj02(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
            if (!mMultiMapView.mMapViewS.isInMapRegion(poiLL)) {
                continue;
            }
            Point ff = Start.getInstance().MapKit().LL2XY(poiLL);
            paint.setColor(Color.parseColor("#AAAF0000"));
            canvas.drawCircle(ff.x * ws, ff.y * ws, dip2px(12), paint);
            String strPrn = (i + 1) + "";
            float textWidth = paint.measureText(strPrn) / 2;
            float textHeight = paint.getTextSize() / 2;
            paint.setColor(Color.WHITE);
            canvas.drawText(strPrn, ff.x * ws - textWidth, ff.y * ws + textHeight - 1,
                    paint);
        }

    }

    private void drawMarker(Canvas canvas, float ws) {
        ArrayList<WayPoint> waypointList = DBDataCenter.getInstance().getWaypointList();
        int count = waypointList.size();
        int resId;
        for (int i = 0; i < count; ++i) {
            WayPoint wp = waypointList.get(i);
            LonLat poiLL = wp.getLL();
            poiLL = Utils.wgs84togcj02(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
            if (!mMultiMapView.mMapViewS.isInMapRegion(poiLL)) {
                continue;
            }
            resId = wp.getTypeIcon();
            Bitmap bm = ((BitmapDrawable) getResources().getDrawable(resId))
                    .getBitmap();
            Point e = Start.getInstance().MapKit().LL2XY(poiLL);
            int x = (int) (e.x * ws - bm.getWidth() / 2);
            int y = (int) (e.y * ws - bm.getHeight() / 2);
            canvas.drawBitmap(bm, x, y, null);

            if (Start.getInstance().MapKit().getScale() > 10000) {
                Paint paint = new Paint();
                paint.reset();
                if (wp.getType() == 1) {
                    paint.setColor(Color.RED);//警告点
                } else {
                    paint.setColor(Color.BLUE);
                }

                int lp = 32;
                paint.setTextSize(13);
                if (SysUtils.getInstance().is240x320) {
                    paint.setTextSize(11);
                    lp = 16;
                }
                paint.setFakeBoldText(true);
                paint.setAntiAlias(true);
                paint.setAlpha(220);
                paint.setUnderlineText(true);
//              paint.measureText(wp.getName());
                String name = wp.getName();
                if (name.length() > 13) {
                    name = wp.getName().substring(0, 13);
                }
                canvas.drawText(name, x + bm.getWidth() - 2, y + lp, paint);
            }

        }
    }


    //======OSM+mapforge
    MapListener mapListener = new MapListener() {
        @Override
        public boolean onScroll(ScrollEvent scrollEvent) {

            return true;
        }

        @Override
        public boolean onZoom(ZoomEvent zoomEvent) {
            return false;
        }

        boolean _isLongPress = false;

        @Override
        public void longPress(Point pt) {
            if (pt == null) {
                return;
            }

            if (mMeasureMode > 0) {
                return;
            }

            removeTip();
            _isLongPress = true;
            if (SysUtils.getInstance().mapsource == 1001) {
                LatLong geoPoint = mMultiMapView.mapView.getMapViewProjection().fromPixels(pt.x, pt.y);
                if (geoPoint != null) {
                    LonLat tipLL = new LonLat(geoPoint.getLongitude(), geoPoint.getLatitude());
                    addMarkByLL(tipLL, null);
                }
            } else {
                IGeoPoint geoPoint = mMultiMapView.mMapViewOnline.getProjection().fromPixels(pt.x, pt.y);
                LonLat tipLL = new LonLat(geoPoint.getLongitude(), geoPoint.getLatitude());
                if (mMultiMapView.isgcj02) {
                    tipLL = Utils.gcj02towgs84(tipLL.GetLon(), tipLL.GetLat());
                }
                //加航点
                if (tipLL != null) {
                    addMarkByLL(tipLL, null);
                }
            }

        }

        //双击
        @Override
        public void doubleClick(Point pt) {
//            if (pt == null) {
//                return;
//            }
            if (mFHandler != null && mMeasureMode == 0) {
                mFHandler.sendEmptyMessage(Msg.DOAUTOTAB);
            }
        }

        //单击 单击后
        @Override
        public void singleClick(Point pt) {
            if (pt == null) {
                return;
            }

            if (mMeasureMode > 0 || mMapMode == NAVI_MODE) {
                return;
            }

            _tipPoint = pt;
            resetTipInfo2(true);
        }

        //移图后抬起
        @Override
        public void touchUp() {
//            if (_isLongPress) {
//                _isLongPress = false;
//                return;
//            }
//            if (mMapMode == MOVING_MODE) {
//                resetTipInfo2(true);
//                return;
//            }
        }

        //手指移动-切换到移图模式
        @Override
        public void moveMap() {
            if (mMapMode != MOVING_MODE) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(Msg.TOMOVINGMODE);
                }
            } else {
//                resetTipInfo2(false);
                resetTipInfo2(true);
            }
        }

    };

    void resetTipInfo2(boolean searching) {
        if (_tipPoint == null) {
            return;
        }

        LonLat tipLL = null;//原始；
        LonLat tipLLH = null;//火星；

        if (SysUtils.getInstance().mapsource == 1001) {
            LatLong geoPoint = mMultiMapView.mapView.getMapViewProjection().fromPixels(_tipPoint.x, _tipPoint.y);
            if (geoPoint == null) {
                return;
            }
            tipLL = new LonLat(geoPoint.getLongitude(), geoPoint.getLatitude());
        } else {
            IGeoPoint geoPoint = mMultiMapView.mMapViewOnline.getProjection().fromPixels(_tipPoint.x, _tipPoint.y);
            tipLL = new LonLat(geoPoint.getLongitude(), geoPoint.getLatitude());
        }

        if (mMultiMapView.isgcj02) {
            tipLLH = tipLL;
            tipLL = Utils.gcj02towgs84(tipLL.GetLon(), tipLL.GetLat());
        } else {
            tipLLH = Utils.wgs84togcj02(tipLL.GetLon(), tipLL.GetLat());
        }

        Start.getInstance().MapKit().setScale(100000);
        //40x40范围内如果有航点，则显示航点信息
        //找到航点的最小矩形范围
        WayPoint wp = DBDataCenter.getInstance().getNearWaypt(tipLL);
        DBDataCenter.getInstance().makerEdit = wp;
        if (wp != null && wp.getDistance() > 50) {
            wp = null;
        }
        if (wp == null) {
            if (searching) {
                //5米以内的poi
                Start.getInstance().MapKit().mTipPoiList = Start.getInstance().MapKit()
                        .getNearPoi(tipLLH, true);
                if (Start.getInstance().MapKit().mTipPoiList.size() > 0) {
                    NavFrameSDK.POIDescription data = Start.getInstance().MapKit().mTipPoiList.get(0);
                    mTipInfo.showBtn();//是否显示两边的按钮
                    mTipInfo.setData(data);
                }
            }
        } else {
            mTipInfo.setText(wp.getName());
        }

        mTipInfo.setLL(tipLL);
        if (mHandler != null) {
            mHandler.sendEmptyMessage(Msg.CHANGEMAPINFO);
        }

        mMultiMapView.mMapViewOnline.invalidate();
        mMultiMapView.mapView.invalidate();
    }

    Polyline _routeline = null;//原始GPS
    Polyline _routelineH = null;//火星坐标

    public void addRoute2Map() {

        if (!Start.getInstance().isHavePath()) {
            _routeline = null;
            _routelineH = null;
            return;
        }

        NavFrameSDK.CLonLat[] routeAllPts = Start.getInstance().MapKit().getPathPts();
        if (routeAllPts == null) {
            return;
        }

        List<GeoPoint> points = new ArrayList<>();
        List<GeoPoint> pointsH = new ArrayList<>();
        for (int i = 0; i < routeAllPts.length; i++) {
            LonLat poiLL = new LonLat(routeAllPts[i].lon, routeAllPts[i].lat);
            pointsH.add(new LabelledGeoPoint(poiLL.GetLat(), poiLL.GetLon(), ""));

            poiLL = Utils.gcj02towgs84(routeAllPts[i].lon, routeAllPts[i].lat);
            points.add(new LabelledGeoPoint(poiLL.GetLat(), poiLL.GetLon(), ""));
        }

        float width = 13;
        if (SysUtils.getInstance().is240x320) {
            width = 7;
        }
        if (points.size() > 2) {
            _routeline = new Polyline();
            _routeline.setWidth(width);
            _routeline.setColor(0xFF1B7BCD);
            _routeline.setPoints(points);

            _routelineH = new Polyline();
            _routelineH.setWidth(width);
            _routelineH.setColor(0xFF1B7BCD);
            _routelineH.setPoints(pointsH);
        }
    }

    private CustomPointOverlay mGisOverlay = null;

    public class CustomPointOverlay extends Overlay {

        private final Point mMapCoordsProjected = new Point();
        private final Point mMapCoordsTranslated = new Point();
        protected Paint mCirclePaint = new Paint();

        int w;
        int h;

        public CustomPointOverlay() {
        }

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {

            if (mMultiMapView.getMapsource() >= 1000 && mMultiMapView.getMapsource() <= 1001) {
                return;
            }

            float ws = getContext().getResources().getDisplayMetrics().density;
            w = mapView.getWidth();
            h = mapView.getHeight();

            BoundingBox bb = mapView.getBoundingBox();//获取当前区域
            double[] regions = {bb.getLonEast(), bb.getLatNorth(), bb.getLonWest(), bb.getLatSouth()};

            //绘制导航路线
            if (_routeline != null) {
                if (mMultiMapView.isgcj02) {
                    _routelineH.draw(canvas, mapView, shadow);
                } else {
                    _routeline.draw(canvas, mapView, shadow);
                }
            }

            MapSetInfo.getInstance().draw2(getContext(), canvas, mapView);
            if (mMapMode == MOVING_MODE) {
                drawLineCar2Tip2(canvas, ws);//ok
            }

            drawLineCar2dest2(canvas, ws);//车到最终目的地的连线 ok
            drawNavDest2(canvas, ws);//目的地icon ok
            drawMeasure2(canvas, ws);//测量 ok

            drawMarker2(canvas, ws);//显示航点 ok

            if (_isNaviByRoute) {
                drawRoute2(canvas, ws);//画航线--?
            }

            PaomaoInfo.getInstance().draw2(getContext(), canvas, mapView, mMultiMapView.isgcj02);//画抛锚点 ok

            TrackShow.getInstance().drawWayTrail2(getContext(), canvas, mapView, null, mMultiMapView.isgcj02);//ok

            if (SysUtils.getInstance()._realtimeArea != -1) {
                MeasureCenter.getInstance().drawmeasureRT2(getContext(), canvas, mapView, mMultiMapView.isgcj02);//?
            }

            mCar.setMapsize(w, h);
            mCar.draw2(getContext(), canvas, mapView, mMultiMapView.isgcj02);//ok
//            mCompass.draw2(getContext(), canvas, (int) mapView.getMapOrientation());

            if (mHandler != null) {
                mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);
            }
        }

        //经纬度坐标到屏幕坐标的转换
        Point LL2XY(LonLat ll) {
            Point B = new Point();
            mMultiMapView.mMapViewOnline.getProjection().toProjectedPixels(ll.GetLat(),
                    ll.GetLon(), mMapCoordsProjected);
            Projection pj = mMultiMapView.mMapViewOnline.getProjection();
            pj.toPixelsFromProjected(mMapCoordsProjected, B);
            return B;
        }

        public void drawLineCar2Tip2(Canvas canvas, float ws) {
            if (mMeasureMode != 0) {
                return;
            }

            //当前位置到tip的连线+大头针
            if (_tipPoint == null) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(Msg.CHANGEMAPINFO);
                }
                return;
            }
            Point A = _tipPoint;
            LonLat a2 = mCar.getCarLL();
            if (mMultiMapView.isgcj02) {
                a2 = Utils.wgs84togcj02(mCar.getCarLL().GetLon(), mCar.getCarLL().GetLat());//Utils GPS to 火星坐标
            }

            Point B = LL2XY(a2);
            LonLat center = mMultiMapView.getMapCenter();
            Point C = LL2XY(center);//501,501

            int w0 = canvas.getWidth();//480
            int h0 = canvas.getHeight();//686
            int w1 = mMultiMapView.mMapViewOnline.getWidth();//480
            int h1 = mMultiMapView.mMapViewOnline.getHeight();//686

            int[] line = {A.x, A.y, B.x, B.y};
            Utils.revisePt(line, w, h);

            PathEffect pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
            Paint paint = new Paint();
            paint.reset();
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(4);
            paint.setColor(Color.RED);
            paint.setAntiAlias(true);
            paint.setPathEffect(pathEffect);
            Path path = new Path();
            path.moveTo(line[0], line[1]);
            path.lineTo(line[2], line[3]);
            canvas.drawPath(path, paint);

            Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.center_marker))
                    .getBitmap();
            int x = (int) (line[0] - bm.getWidth());
            int y = (int) (line[1] - bm.getHeight());
            canvas.drawBitmap(bm, x, y, null);
        }

        public void drawLineCar2dest2(Canvas canvas, float ws) {
            if (!Start.getInstance().isHavePath())
                return;

            if (Start.getInstance().MapKit().mNavDest == null || mCar == null) {
                return;
            }
            int size = Start.getInstance().MapKit().mNavDest.length;
            if (size < 1)
                return;

            int indexDest = size - 1;
            float[] ff = new float[4];
            LonLat destLL = new LonLat(
                    Start.getInstance().MapKit().mNavDest[indexDest].pos.lon,
                    Start.getInstance().MapKit().mNavDest[indexDest].pos.lat);

            LonLat a2 = destLL;//Utils 火星坐标 to GPS
            if (!mMultiMapView.isgcj02) {
                a2 = Utils.gcj02towgs84(destLL.GetLon(), destLL.GetLat());
            }

            Point d = LL2XY(a2);
            ff[0] = d.x;
            ff[1] = d.y;

            a2 = mCar.getCarLL();//原始坐标
            if (mMultiMapView.isgcj02) {
                a2 = Utils.wgs84togcj02(mCar.getCarLL().GetLon(), mCar.getCarLL().GetLat());
            }

            Point carpos = LL2XY(a2);
            ff[2] = carpos.x;
            ff[3] = carpos.y;

            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setColor(Color.RED);
            paint.setStrokeWidth((float) 3.0);
            canvas.drawLines(ff, paint);
        }

        private void drawNavDest2(Canvas canvas, float ws) {
            if (!Start.getInstance().isHavePath())
                return;

            BoundingBox bb = mMultiMapView.mMapViewOnline.getBoundingBox();//获取当前区域
            double[] regions = {bb.getLonEast(), bb.getLatNorth(), bb.getLonWest(), bb.getLatSouth()};

            if (Start.getInstance().MapKit().mNavDest != null
                    && Start.getInstance().MapKit().mNavDest.length > 0) {
                int count = Start.getInstance().MapKit().mNavDest.length;
                int resId = R.drawable.destination;
                for (int i = 0; i < count; ++i) {

                    LonLat poiLL = new LonLat(Start.getInstance().MapKit().mNavDest[i].pos.lon,
                            Start.getInstance().MapKit().mNavDest[i].pos.lat);
                    if (!mMultiMapView.isgcj02) {
                        poiLL = Utils.gcj02towgs84(Start.getInstance().MapKit().mNavDest[i].pos.lon,
                                Start.getInstance().MapKit().mNavDest[i].pos.lat);//Utils GPS to 火星坐标
                    }

                    if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                            || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                        continue;
                    }

                    Point e = LL2XY(poiLL);
                    int z = 1;
                    if (i == count - 1) {
                        resId = R.drawable.destination;
                        z = 2;
                    } else {
                        resId = R.drawable.marker01 + i;
                        if (resId > R.drawable.marker15) {
                            resId = R.drawable.marker15;
                        }
                    }

                    Bitmap bm = ((BitmapDrawable) getResources().getDrawable(resId))
                            .getBitmap();
                    int x = (int) (e.x - bm.getWidth() / 2);
                    int y = (int) (e.y - bm.getHeight() / z);
                    canvas.drawBitmap(bm, x, y, null);
                }
            }
        }

        private void drawMeasure2(Canvas canvas, float ws) {
            int count = Start.getInstance().mMeasurelist.size();
            if (count < 1) {
                return;
            }

            BoundingBox bb = mMultiMapView.mMapViewOnline.getBoundingBox();//获取当前区域
            double[] regions = {bb.getLonEast(), bb.getLatNorth(), bb.getLonWest(), bb.getLatSouth()};

            Paint paint = new Paint();
            paint.reset();
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(4);
            paint.setColor(Color.parseColor("#AA0000FF"));
            paint.setAntiAlias(true);
            PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
            paint.setPathEffect(pathEffect);
            Path path = new Path();

            if (count >= 2) {
                Point AA = null;
                int ii = -1;
                for (int i = 1; i < count; ++i) {
                    LonLat poiLLA = Start.getInstance().mMeasurelist.get(i - 1);
                    LonLat poiLLB = Start.getInstance().mMeasurelist.get(i);

                    if (mMultiMapView.isgcj02) {
                        poiLLA = Utils.wgs84togcj02(poiLLA.GetLon(), poiLLA.GetLat());//Utils GPS to 火星坐标
                        poiLLB = Utils.wgs84togcj02(poiLLB.GetLon(), poiLLB.GetLat());//Utils GPS to 火星坐标
                    }

                    if (i == count - 1 && _measureisgcj02 == mMultiMapView.isgcj02 && _measureLL != null) {
                        poiLLB = _measureLL;
                    }

                    double[] lineLL = {poiLLA.GetLon(), poiLLA.GetLat(), poiLLB.GetLon(), poiLLB.GetLat()};
                    if (!Utils.isLineIntersectRectangle(regions, lineLL)) {
                        continue;
                    }
                    Point A = null;
                    if (AA != null && ii == i - 1) {
                        A = AA;
                    } else {
                        A = LL2XY(poiLLA);//耗时操作能省则省
                    }
                    Point B = LL2XY(poiLLB);
                    AA = B;
                    int[] line = {A.x, A.y, B.x, B.y};
                    if (Utils.revisePt(line, w, h)) {
                        path.moveTo(line[0], line[1]);
                        path.lineTo(line[2], line[3]);
                    }
                }

                if (mMeasureMode == 2) {
                    //目前主地图不测面积，如需测面积需回复原画线方式
                    path.close();//封闭
                    paint.setColor(Color.LTGRAY);
                }

                canvas.drawPath(path, paint);

                if (mMeasureMode == 2) {
                    paint.setColor(Color.parseColor("#AAFF0000"));
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawPath(path, paint);
                }
            }

            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(13);
            paint.setFakeBoldText(true);

            for (int i = 0; i < count; ++i) {
                LonLat poiLL = Start.getInstance().mMeasurelist.get(i);

                if (mMultiMapView.isgcj02) {
                    poiLL = Utils.wgs84togcj02(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
                }

                if (i == count - 1 && _measureisgcj02 == mMultiMapView.isgcj02 && _measureLL != null) {
                    poiLL = _measureLL;
                }

                if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                        || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                    continue;
                }

                paint.setColor(Color.parseColor("#AAFF0000"));
                Point ff = LL2XY(poiLL);
                canvas.drawCircle(ff.x, ff.y, dip2px(12), paint);
                String strPrn = (i + 1) + "";
                float textWidth = paint.measureText(strPrn) / 2;
                float textHeight = paint.getTextSize() / 2;
                paint.setColor(Color.WHITE);
                canvas.drawText(strPrn, ff.x - textWidth, ff.y + textHeight - 1,
                        paint);
            }

        }

        private void drawRoute2(Canvas canvas, float ws) {

            BoundingBox bb = mMultiMapView.mMapViewOnline.getBoundingBox();//获取当前区域
            double[] regions = {bb.getLonEast(), bb.getLatNorth(), bb.getLonWest(), bb.getLatSouth()};

            PathEffect pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.parseColor("#AA0000FF"));
            paint.setStrokeWidth(4);
            paint.setAntiAlias(true);
            paint.setPathEffect(pathEffect);
            Path path = new Path();

            Point AA = null;
            int ii = -1;
            int count = DBDataCenter.getInstance().routeNavi.waypointList.size();
            for (int i = 1; i < count; ++i) {
                LonLat poiLLA = DBDataCenter.getInstance().routeNavi.waypointList.get(i - 1).getLL();
                LonLat poiLLB = DBDataCenter.getInstance().routeNavi.waypointList.get(i).getLL();

                if (mMultiMapView.isgcj02) {
                    poiLLA = Utils.wgs84togcj02(poiLLA.GetLon(), poiLLA.GetLat());//Utils GPS to 火星坐标
                    poiLLB = Utils.wgs84togcj02(poiLLB.GetLon(), poiLLB.GetLat());//Utils GPS to 火星坐标
                }

                double[] lineLL = {poiLLA.GetLon(), poiLLA.GetLat(), poiLLB.GetLon(), poiLLB.GetLat()};
                if (!Utils.isLineIntersectRectangle(regions, lineLL)) {
                    continue;
                }

                Point A = null;
                if (AA != null && ii == i - 1) {
                    A = AA;
                } else {
                    A = LL2XY(poiLLA);//耗时操作能省则省
                }
                Point B = LL2XY(poiLLB);
                AA = B;
                ii = i;

                int[] line = {A.x, A.y, B.x, B.y};
                if (Utils.revisePt(line, w, h)) {
                    path.moveTo(line[0], line[1]);
                    path.lineTo(line[2], line[3]);
                }
            }

            canvas.drawPath(path, paint);

            //画icon
            paint.setStyle(Paint.Style.FILL);
            paint.setTextSize(13);
            paint.setFakeBoldText(true);

            for (int i = 0; i < count; ++i) {
                LonLat poiLL = DBDataCenter.getInstance().routeNavi.waypointList.get(i).getLL();
                if (mMultiMapView.isgcj02) {
                    poiLL = Utils.wgs84togcj02(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
                }
                if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                        || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                    continue;
                }

                Point ff = LL2XY(poiLL);
                paint.setColor(Color.parseColor("#AAAF0000"));
                canvas.drawCircle(ff.x, ff.y, dip2px(12), paint);
                String strPrn = (i + 1) + "";
                float textWidth = paint.measureText(strPrn) / 2;
                float textHeight = paint.getTextSize() / 2;
                paint.setColor(Color.WHITE);
                canvas.drawText(strPrn, ff.x - textWidth, ff.y + textHeight - 1,
                        paint);
            }

        }

        private void drawMarker2(Canvas canvas, float ws) {
            BoundingBox bb = mMultiMapView.mMapViewOnline.getBoundingBox();//获取当前区域
            double[] regions = {bb.getLonEast(), bb.getLatNorth(), bb.getLonWest(), bb.getLatSouth()};

            ArrayList<WayPoint> waypointList = DBDataCenter.getInstance().getWaypointList();
            int count = waypointList.size();
            int resId;
            for (int i = 0; i < count; ++i) {
                WayPoint wp = waypointList.get(i);
                LonLat poiLL = wp.getLL();
                if (mMultiMapView.isgcj02) {
                    poiLL = Utils.wgs84togcj02(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
                }

                if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                        || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                    continue;
                }
                resId = wp.getTypeIcon();
                Bitmap bm = ((BitmapDrawable) getResources().getDrawable(resId))
                        .getBitmap();
                Point e = LL2XY(poiLL);
                int x = (int) (e.x - bm.getWidth() / 2);
                int y = (int) (e.y - bm.getHeight() / 2);
                canvas.drawBitmap(bm, x, y, null);

                if (Start.getInstance().MapKit().getScale() > 10000) {
                    Paint paint = new Paint();
                    paint.reset();
                    if (wp.getType() == 1) {
                        paint.setColor(Color.RED);//警告点
                    } else {
                        paint.setColor(Color.BLUE);
                    }
                    int lp = 32;
                    paint.setTextSize(13);
                    if (SysUtils.getInstance().is240x320) {
                        paint.setTextSize(11);
                        lp = 16;
                    }
                    paint.setFakeBoldText(true);
                    paint.setAntiAlias(true);
                    paint.setAlpha(220);
                    paint.setUnderlineText(true);
//              paint.measureText(wp.getName());
                    String name = wp.getName();
                    if (name.length() > 12) {
                        name = wp.getName().substring(0, 12);
                    }
                    canvas.drawText(name, x + bm.getWidth() - 2, y + lp, paint);
                }

            }
        }

    }


    //======Mapsforge
    MapsforgeLayer mapsforgeLayer = new MapsforgeLayer();

    public class MapsforgeLayer extends Layer {

        int w, h;

        org.mapsforge.core.model.BoundingBox bb;
        byte zoomLevel;
        org.mapsforge.core.graphics.Canvas canvas;
        org.mapsforge.core.model.Point topLeftPoint;

        public MapsforgeLayer() {
        }

        @Override
        public synchronized void draw(org.mapsforge.core.model.BoundingBox bb, byte zoomLevel, org.mapsforge.core.graphics.Canvas canvas, org.mapsforge.core.model.Point topLeftPoint) {

            if (mMultiMapView.getMapsource() != 1001) {
                return;
            }

            android.graphics.Canvas androidCanvas = AndroidGraphicFactory.getCanvas(canvas);

            this.bb = bb;
            this.zoomLevel = zoomLevel;
            this.canvas = canvas;
            this.topLeftPoint = topLeftPoint;

            w = canvas.getWidth();//1004
            h = canvas.getHeight();//1004

            double[] regions = {bb.maxLongitude, bb.maxLatitude, bb.minLongitude, bb.minLatitude};

            MapSetInfo.getInstance().draw3(getContext(), canvas, bb, zoomLevel, topLeftPoint, displayModel);
            if (mMapMode == MOVING_MODE) {
                drawLineCar2Tip3(androidCanvas);//ok
            }

            drawLineCar2dest3();//车到最终目的地的连线 ok
            drawNavDest3();//目的地icon ok
            drawMeasure3();//测量 ok

            drawMarker3();//显示航点 ok

            if (_isNaviByRoute) {
                drawRoute3();//画航线--?
            }

            PaomaoInfo.getInstance().draw3(getContext(), canvas, bb, zoomLevel, topLeftPoint, displayModel);//画抛锚点 ok

            TrackShow.getInstance().drawWayTrail3(getContext(), androidCanvas, bb, zoomLevel, topLeftPoint, displayModel, null);//ok

            if (SysUtils.getInstance()._realtimeArea != -1) {
                MeasureCenter.getInstance().drawmeasureRT3(getContext(), androidCanvas, bb, zoomLevel, topLeftPoint, displayModel);//?
            }

            mCar.setMapsize(w, h);
            mCar.draw3(getContext(), canvas, bb, zoomLevel, topLeftPoint, displayModel);//ok
//            mCompass.draw3(getContext(), canvas, 0, bb, zoomLevel, topLeftPoint, displayModel);

            if (mHandler != null) {
                mHandler.sendEmptyMessage(Msg.FINISHUPDATEMAP);
            }

        }

        //经纬度坐标到屏幕坐标的转换
        Point LL2XY(LonLat ll) {
            long mapSize = MercatorProjection.getMapSize(zoomLevel, displayModel.getTileSize());
            int x = (int) (MercatorProjection.longitudeToPixelX(ll.GetLon(), mapSize) - topLeftPoint.x);
            int y = (int) (MercatorProjection.latitudeToPixelY(ll.GetLat(), mapSize) - topLeftPoint.y);
            Point B = new Point(x, y);
            return B;
        }

        public void drawLineCar2Tip3(Canvas canvas) {
            if (mMeasureMode != 0) {
                return;
            }

            //当前位置到tip的连线+大头针
            if (_tipPoint == null) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(Msg.CHANGEMAPINFO);
                }
                return;
            }
            Point A = _tipPoint;
            LonLat a2 = mCar.getCarLL();
            Point B = LL2XY(a2);

            LonLat center = mMultiMapView.getMapCenter();
            Point C = LL2XY(center);//501,501

            int w0 = canvas.getWidth();//837
            int h0 = canvas.getHeight();//837
            int w1 = mMultiMapView.mapView.getWidth();//837
            int h1 = mMultiMapView.mapView.getHeight();//837

            int ax = (int) (A.x * w * 1.0 / w1);
            int ay = (int) (A.y * h * 1.0 / h1);
            int[] line = {ax, ay, B.x, B.y};
            Utils.revisePt(line, w, h);

            PathEffect pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
            Paint paint = new Paint();
            paint.reset();
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(4);
            paint.setColor(Color.RED);
            paint.setAntiAlias(true);
            paint.setPathEffect(pathEffect);
            Path path = new Path();
            path.moveTo(line[0], line[1]);
            path.lineTo(line[2], line[3]);
            canvas.drawPath(path, paint);

            Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.center_marker))
                    .getBitmap();
            int x = (int) (line[0] - bm.getWidth());
            int y = (int) (line[1] - bm.getHeight());
            canvas.drawBitmap(bm, x, y, null);
        }

        public void drawLineCar2dest3() {
            if (!Start.getInstance().isHavePath())
                return;

            if (Start.getInstance().MapKit().mNavDest == null || mCar == null) {
                return;
            }
            int size = Start.getInstance().MapKit().mNavDest.length;
            if (size < 1)
                return;

            int indexDest = size - 1;
            int[] ff = new int[4];
            LonLat destLL = new LonLat(
                    Start.getInstance().MapKit().mNavDest[indexDest].pos.lon,
                    Start.getInstance().MapKit().mNavDest[indexDest].pos.lat);

            destLL = Utils.gcj02towgs84(destLL.GetLon(), destLL.GetLat());
            Point d = LL2XY(destLL);
            ff[0] = d.x;
            ff[1] = d.y;

            Point carpos = LL2XY(mCar.getCarLL());
            ff[2] = carpos.x;
            ff[3] = carpos.y;

            org.mapsforge.core.graphics.Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
            paint.setStyle(Style.STROKE);
            paint.setColor(Color.RED);
            paint.setStrokeWidth((float) 3.0);

            canvas.drawLine(ff[0], ff[1], ff[2], ff[3], paint);
        }

        private void drawNavDest3() {
            if (!Start.getInstance().isHavePath())
                return;

            double[] regions = {bb.maxLongitude, bb.maxLatitude, bb.minLongitude, bb.minLatitude};

            Paint paintZ = new Paint();

            if (Start.getInstance().MapKit().mNavDest != null
                    && Start.getInstance().MapKit().mNavDest.length > 0) {
                int count = Start.getInstance().MapKit().mNavDest.length;
                int resId = R.drawable.destination;
                for (int i = 0; i < count; ++i) {
                    LonLat poiLL = new LonLat(
                            Start.getInstance().MapKit().mNavDest[i].pos.lon,
                            Start.getInstance().MapKit().mNavDest[i].pos.lat);

                    poiLL = Utils.gcj02towgs84(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
                    if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                            || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                        continue;
                    }

                    Point e = LL2XY(poiLL);
                    int z = 1;
                    if (i == count - 1) {
                        resId = R.drawable.destination;
                        z = 2;
                    } else {
                        resId = R.drawable.marker01 + i;
                        if (resId > R.drawable.marker15) {
                            resId = R.drawable.marker15;
                        }
                    }

                    org.mapsforge.core.graphics.Bitmap bm = AndroidGraphicFactory.convertToBitmap(getResources().getDrawable(resId), paintZ);

                    int x = (int) (e.x - bm.getWidth() / 2);
                    int y = (int) (e.y - bm.getHeight() / z);
                    canvas.drawBitmap(bm, x, y);
                }
            }
        }

        private void drawMeasure3() {
            int count = Start.getInstance().mMeasurelist.size();
            if (count < 1) {
                return;
            }

            double[] regions = {bb.maxLongitude, bb.maxLatitude, bb.minLongitude, bb.minLatitude};

            org.mapsforge.core.graphics.Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
            paint.setStyle(Style.STROKE);
            paint.setColor(Color.parseColor("#AA0000FF"));
            paint.setStrokeWidth(4);
            paint.setDashPathEffect(new float[]{5, 5, 5, 5});

            org.mapsforge.core.graphics.Path path = AndroidGraphicFactory.INSTANCE.createPath();

            if (count >= 2) {
                Point AA = null;
                int ii = -1;
                for (int i = 1; i < count; ++i) {
                    LonLat poiLLA = Start.getInstance().mMeasurelist.get(i - 1);
                    LonLat poiLLB = Start.getInstance().mMeasurelist.get(i);

                    if (i == count - 1 && !_measureisgcj02 && _measureLL != null) {
                        poiLLB = _measureLL;
                    }

                    double[] lineLL = {poiLLA.GetLon(), poiLLA.GetLat(), poiLLB.GetLon(), poiLLB.GetLat()};
                    if (!Utils.isLineIntersectRectangle(regions, lineLL)) {
                        continue;
                    }
                    Point A = null;
                    if (AA != null && ii == i - 1) {
                        A = AA;
                    } else {
                        A = LL2XY(poiLLA);//耗时操作能省则省
                    }
                    Point B = LL2XY(poiLLB);
                    AA = B;
                    int[] line = {A.x, A.y, B.x, B.y};
                    if (Utils.revisePt(line, w, h)) {
                        path.moveTo(line[0], line[1]);
                        path.lineTo(line[2], line[3]);
                    }
                }

                if (mMeasureMode == 2) {
                    //目前主地图不测面积，如需测面积需回复原画线方式
                    path.close();//封闭
                    paint.setColor(Color.LTGRAY);
                }

                canvas.drawPath(path, paint);

                if (mMeasureMode == 2) {
                    paint.setColor(Color.parseColor("#AAFF0000"));
                    paint.setStyle(Style.FILL);
                    canvas.drawPath(path, paint);
                }
            }

            paint.setStyle(Style.FILL);
            paint.setTextSize(13);

            Paint paintZ = new Paint();
            paintZ.setTextSize(13);

            for (int i = 0; i < count; ++i) {
                LonLat poiLL = Start.getInstance().mMeasurelist.get(i);

                if (i == count - 1 && !_measureisgcj02 && _measureLL != null) {
                    poiLL = _measureLL;
                }

                if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                        || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                    continue;
                }

                paint.setColor(Color.parseColor("#AAFF0000"));
                Point ff = LL2XY(poiLL);
                canvas.drawCircle(ff.x, ff.y, dip2px(12), paint);
                String strPrn = (i + 1) + "";
                float textWidth = paintZ.measureText(strPrn) / 2;
                float textHeight = paintZ.getTextSize() / 2;
                paint.setColor(Color.WHITE);
                canvas.drawText(strPrn, (int) (ff.x - textWidth), (int) (ff.y + textHeight - 1),
                        paint);
            }

        }

        private void drawRoute3() {

            double[] regions = {bb.maxLongitude, bb.maxLatitude, bb.minLongitude, bb.minLatitude};

            org.mapsforge.core.graphics.Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
            paint.setStyle(Style.STROKE);
            paint.setColor(Color.parseColor("#AA0000FF"));
            paint.setStrokeWidth(4);
            paint.setDashPathEffect(new float[]{5, 5, 5, 5});

            org.mapsforge.core.graphics.Path path = AndroidGraphicFactory.INSTANCE.createPath();

            Point AA = null;
            int ii = -1;
            int count = DBDataCenter.getInstance().routeNavi.waypointList.size();
            for (int i = 1; i < count; ++i) {
                LonLat poiLLA = DBDataCenter.getInstance().routeNavi.waypointList.get(i - 1).getLL();
                LonLat poiLLB = DBDataCenter.getInstance().routeNavi.waypointList.get(i).getLL();

                double[] lineLL = {poiLLA.GetLon(), poiLLA.GetLat(), poiLLB.GetLon(), poiLLB.GetLat()};
                if (!Utils.isLineIntersectRectangle(regions, lineLL)) {
                    continue;
                }

                Point A = null;
                if (AA != null && ii == i - 1) {
                    A = AA;
                } else {
                    A = LL2XY(poiLLA);//耗时操作能省则省
                }
                Point B = LL2XY(poiLLB);
                AA = B;
                ii = i;

                int[] line = {A.x, A.y, B.x, B.y};
                if (Utils.revisePt(line, w, h)) {
                    path.moveTo(line[0], line[1]);
                    path.lineTo(line[2], line[3]);
                }
            }

            canvas.drawPath(path, paint);
            //画icon
            paint.setStyle(Style.FILL);
            paint.setTextSize(13);

            Paint paintZ = new Paint();
            paintZ.setTextSize(13);

            for (int i = 0; i < count; ++i) {
                LonLat poiLL = DBDataCenter.getInstance().routeNavi.waypointList.get(i).getLL();
                if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                        || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                    continue;
                }

                Point ff = LL2XY(poiLL);
                paint.setColor(Color.parseColor("#AAAF0000"));
                canvas.drawCircle(ff.x, ff.y, dip2px(12), paint);
                String strPrn = (i + 1) + "";
                float textWidth = paintZ.measureText(strPrn) / 2;
                float textHeight = paintZ.getTextSize() / 2;
                paint.setColor(Color.WHITE);
                canvas.drawText(strPrn, (int) (ff.x - textWidth), (int) (ff.y + textHeight - 1),
                        paint);
            }

        }

        private void drawMarker3() {
            double[] regions = {bb.maxLongitude, bb.maxLatitude, bb.minLongitude, bb.minLatitude};

            ArrayList<WayPoint> waypointList = DBDataCenter.getInstance().getWaypointList();
            int count = waypointList.size();
            int resId;
            Paint paintZ = new Paint();

            for (int i = 0; i < count; ++i) {
                WayPoint wp = waypointList.get(i);
                LonLat poiLL = wp.getLL();
                if (poiLL.GetLon() > regions[0] || poiLL.GetLat() > regions[1]
                        || poiLL.GetLon() < regions[2] || poiLL.GetLat() < regions[3]) {
                    continue;
                }
                resId = wp.getTypeIcon();

                org.mapsforge.core.graphics.Bitmap bm = AndroidGraphicFactory.convertToBitmap(getResources().getDrawable(resId), paintZ);

                Point e = LL2XY(poiLL);
                int x = (int) (e.x - bm.getWidth() / 2);
                int y = (int) (e.y - bm.getHeight() / 2);

                canvas.drawBitmap(bm, x, y);

                if (Start.getInstance().MapKit().getScale() > 10000) {
                    org.mapsforge.core.graphics.Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
                    paint.setStyle(Style.STROKE);

                    if (wp.getType() == 1) {
                        paint.setColor(Color.RED);//警告点
                    } else {
                        paint.setColor(Color.BLUE);
                    }
                    int lp = 32;
                    paint.setTextSize(13);
                    if (SysUtils.getInstance().is240x320) {
                        paint.setTextSize(11);
                        lp = 16;
                    }

                    String name = wp.getName();
                    if (name.length() > 12) {
                        name = wp.getName().substring(0, 12);
                    }
                    canvas.drawText(name, x + bm.getWidth() - 2, y + lp, paint);
                }

            }
        }

    }

    static org.mapsforge.core.graphics.Paint createPaint(int color, int strokeWidth, Style style) {
        org.mapsforge.core.graphics.Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
        paint.setColor(color);
        paint.setStrokeWidth(strokeWidth);
        paint.setStyle(style);
        return paint;
    }

    org.mapsforge.map.layer.overlay.Polyline _routelineMapsforge = null;

    public void addRoute2MapMapsforge() {

        if (!Start.getInstance().isHavePath()) {
            if (_routelineMapsforge != null) {
                mMultiMapView.mapView.getLayerManager().getLayers().remove(_routelineMapsforge);
                _routelineMapsforge.getLatLongs().clear();
            }
            return;
        }
        if (_routelineMapsforge != null) {
            mMultiMapView.mapView.getLayerManager().getLayers().remove(_routelineMapsforge);
            _routelineMapsforge.getLatLongs().clear();
        } else {
            int strokeWidth = 13;
            if (SysUtils.getInstance().is240x320) {
                strokeWidth = 6;
            }
            org.mapsforge.core.graphics.Paint paintStroke = createPaint(
                    AndroidGraphicFactory.INSTANCE.createColor(0xFF, 0x1B, 0x7B, 0xCD),
                    strokeWidth, Style.STROKE);
            _routelineMapsforge = new org.mapsforge.map.layer.overlay.Polyline(paintStroke, AndroidGraphicFactory.INSTANCE);
        }

        if (!Start.getInstance().isHavePath())
            return;

        NavFrameSDK.CLonLat[] routeAllPts = Start.getInstance().MapKit().getPathPts();
        if (routeAllPts == null) {
            return;
        }

        for (int i = 0; i < routeAllPts.length; i++) {
            LonLat poiLL = new LonLat(routeAllPts[i].lon, routeAllPts[i].lat);
            poiLL = Utils.gcj02towgs84(poiLL.GetLon(), poiLL.GetLat());//Utils GPS to 火星坐标
            _routelineMapsforge.getLatLongs().add(new LatLong(poiLL.GetLat(), poiLL.GetLon()));
        }

        if (_routelineMapsforge.getLatLongs().size() > 2) {
            mMultiMapView.mapView.getLayerManager().getLayers().add(_routelineMapsforge);
        }
    }


    int dip2px(int dip) {
        return Utils.dip2px(getContext(), dip);
    }

}